Пример #1
0
        public void New_FactoryWithFactoryService_ShouldSucceed()
        {
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            serviceCollection.AddTransient <TestServiceTwoParams <IFactory <string, TestServiceOneParam <string> >, double> >();
            serviceCollection.AddTransient <TestServiceOneParam <string> >();
            serviceCollection.AddFactoryFacility();
            var serviceProvider = serviceCollection.BuildServiceProvider();

            var factory = serviceProvider.GetRequiredService <IFactory <double, TestServiceTwoParams <IFactory <string, TestServiceOneParam <string> >, double> > >();

            var instance = factory.New(1);

            instance.Arg2.Should().Be(1);

            var instance2 = factory.New(2);

            instance2.Arg2.Should().Be(2);

            var factory2 = instance.Arg1;

            var instance3 = factory2.New("a");

            instance3.Arg.Should().Be("a");

            var instance4 = factory2.New("b");

            instance4.Arg.Should().Be("b");
        }
Пример #2
0
        public void GetRequiredService_NestedDependencyNotRegistered_ShouldThrow()
        {
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            serviceCollection.AddTransient <TestServiceOneParam <WrongConstructor> >();
            serviceCollection.AddTransient <WrongConstructor>();
            var serviceProvider = serviceCollection.BuildServiceProvider();

            Func <TestServiceOneParam <WrongConstructor> > factory = () => serviceProvider.GetRequiredService <TestServiceOneParam <WrongConstructor> >();

            // This is actually checking already built-in behaviour, but illustrates the kind of exception thrown which we want to align with here
            factory.Should().Throw <InvalidOperationException>()
            .WithMessage($"Unable to resolve service for type '{typeof(double)}' while attempting to activate '{typeof(WrongConstructor)}'.");
        }
Пример #3
0
        static void Main(string[] args)
        {
            //build DI Services
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            serviceCollection.AddTransient <MainApp>();
            serviceCollection.AddTransient <ISalaryFormula, SalaryFormula>();
            //serviceCollection.AddTransient<ISalaryFormula, BossSalaryFormula>();
            var serviceProvider = serviceCollection.BuildServiceProvider();

            //run MainApp.Main with DI
            serviceProvider.GetRequiredService <MainApp>().Main();

            Console.ReadKey();
        }
Пример #4
0
        public async Task PlayTest002()
        {
            var services = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            services.AddScoped <PlayService>();
            services.AddRequestPipe(config => {
                //config.Solver
            }, register => { });
            services.AddTransient <IRequestHandler <PlayRequest, PlayResponse>, PlayRequestHandler>();
            using (var serviceProviderRoot = services.BuildServiceProvider()) {
                using (var scope = serviceProviderRoot.CreateScope()) {
                    var scopeServices          = scope.ServiceProvider;
                    PlayRequestHandler handler = PlayRequestHandler.Create(scopeServices);
                    var responce = await handler.ExecuteAsync(
                        new PlayRequest()
                    {
                        A = 2, B = 40
                    },
                        CancellationToken.None,
                        new RequestHandlerExecutionContext());

                    Assert.Equal(42, responce.Sum);
                }
            }
        }
        public void UsingValueFunction_CreateByFunction_Test1()
        {
            var services = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            services.AddTransient <Dummy>();
            using (var serviceProvider = services.BuildServiceProvider()) {
                var u = UsingValue.CreateByServiceProvider <Dummy>(serviceProvider);
                Assert.NotNull(u);

                // first creation
                var d = u.GetValue();
                Assert.NotNull(d);
                Assert.Same(d, u.GetValue());
                Assert.False(d.IsDisposed);

                // GetValue does not change
                Assert.Equal(0, u.GetValue().Value);
                d.Value = 2;
                Assert.False(u.GetValue().IsDisposed);
                Assert.Equal(2, u.GetValue().Value);

                u.Dispose();
                Assert.True(d.IsDisposed);
            }
        }
Пример #6
0
 public static void ConfigureServices(ServiceCollection services)
 {
     services.AddLogging();
     services.AddOptions();
     //			services.Configure<FBoxClientParameters>(_configuration.GetSection("FBox"));
     services.AddTransient <FBoxDemo>();
 }
Пример #7
0
        public void ConfigureServices()
        {
            var services = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            services.AddControllersAsServices(typeof(Startup).Assembly.GetExportedTypes()
                                              .Where(t => !t.IsAbstract && !t.IsGenericTypeDefinition)
                                              .Where(t => typeof(IController).IsAssignableFrom(t) ||
                                                     t.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)));

            //Register now all repositories
            services.AddTransient <IAccountRepository, AccountRepository>();
            services.AddTransient <IHelperRepository, HelperRepository>();

            var resolver = new DefaultDependencyResolver(services.BuildServiceProvider());

            DependencyResolver.SetResolver(resolver);
        }
Пример #8
0
        static IServiceProvider CreateContainer()
        {
            var services = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            //GitTrends Services
            services.AddSingleton <AzureFunctionsApiService>();
            services.AddSingleton <BackgroundFetchService>();
            services.AddSingleton <DeepLinkingService>();
            services.AddSingleton <NotificationService, ExtendedNotificationService>();
            services.AddSingleton <GitHubApiV3Service>();
            services.AddSingleton <GitHubAuthenticationService>();
            services.AddSingleton <GitHubGraphQLApiService>();
            services.AddSingleton <GitHubUserService>();
            services.AddSingleton <FavIconService>();
            services.AddSingleton <FirstRunService>();
            services.AddSingleton <MediaElementService>();
            services.AddSingleton <ReferringSitesDatabase>();
            services.AddSingleton <RepositoryDatabase>();
            services.AddSingleton <ReviewService>();
            services.AddSingleton <SortingService>();
            services.AddSingleton <SyncfusionService>();
            services.AddSingleton <ThemeService>();
            services.AddSingleton <TrendsChartSettingsService>();

            //GitTrends ViewModels
            services.AddTransient <OnboardingViewModel>();
            services.AddTransient <ReferringSitesViewModel>();
            services.AddTransient <SplashScreenViewModel>();

            //Mocks
            services.AddSingleton <IAnalyticsService, MockAnalyticsService>();
            services.AddSingleton <IAppInfo, MockAppInfo>();
            services.AddSingleton <IBrowser, MockBrowser>();
            services.AddSingleton <IFileSystem, MockFileSystem>();
            services.AddSingleton <IEmail, MockEmail>();
            services.AddSingleton <ILauncher, MockLauncher>();
            services.AddSingleton <IMainThread, MockMainThread>();
            services.AddSingleton <INotificationService, MockNotificationService>();
            services.AddSingleton <INotificationManager, MockNotificationManager>();
            services.AddSingleton <ISecureStorage, MockSecureStorage>();
            services.AddSingleton <IPreferences, MockPreferences>();
            services.AddSingleton <IVersionTracking, MockVersionTracking>();

            return(services.BuildServiceProvider());
        }
Пример #9
0
        public void ShouldInjectFactoryRespectingLifestyle()
        {
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            serviceCollection.AddSingleton <TestSingleton>();
            serviceCollection.AddTransient <TestTransient>();
            serviceCollection.AddTransient <TestService>();
            serviceCollection.AddFactoryFacility();
            var serviceProvider = serviceCollection.BuildServiceProvider();

            var testService = serviceProvider.GetRequiredService <TestService>();

            testService.TransientFactory.New().Should().NotBeSameAs(testService.TransientFactory.New());

            testService.TestTransient.Should().NotBeSameAs(testService.TransientFactory.New());

            testService.SingletonFactory.New().Should().BeSameAs(testService.SingletonFactory.New());

            testService.TestSingleton.Should().BeSameAs(testService.SingletonFactory.New());
        }
Пример #10
0
        public void New_FactoryOfOneArgForRegisteredInterface_ShouldSucceed()
        {
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            serviceCollection.AddTransient <ITestInterfaceOneParam <string>, TestServiceOneParam <string> >();
            serviceCollection.AddFactoryFacility();
            var serviceProvider = serviceCollection.BuildServiceProvider();

            var factory = serviceProvider.GetRequiredService <IFactory <string, ITestInterfaceOneParam <string> > >();

            factory.New("a").Arg.Should().Be("a");
            factory.New("b").Arg.Should().Be("b");
        }
Пример #11
0
        public void GetRequiredService_FactoryOfOneArgForTypeWithTwoMatchingConstructors_ShouldThrow()
        {
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            serviceCollection.AddTransient <TwoConstructors>();
            serviceCollection.AddFactoryFacility();
            var serviceProvider = serviceCollection.BuildServiceProvider();

            Func <IFactory <int, TwoConstructors> > factory = () => serviceProvider.GetRequiredService <IFactory <int, TwoConstructors> >();

            factory.Should().Throw <InvalidOperationException>()
            .WithMessage($"In order to resolve a parameterised factory for service type '{typeof(TwoConstructors)}', the implementation type '{typeof(TwoConstructors)}' must contain just one constructor whose last parameter is assignable from the factory argument type '{typeof(int)}'.");
        }
Пример #12
0
        public void New_FactoryOfOneArgOfAssignableType_ShouldSucceed()
        {
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            serviceCollection.AddTransient <TestServiceOneParam <IEnumerable <string> > >();
            serviceCollection.AddFactoryFacility();
            var serviceProvider = serviceCollection.BuildServiceProvider();

            var factory = serviceProvider.GetRequiredService <IFactory <string[], TestServiceOneParam <IEnumerable <string> > > >();

            factory.New(new[] { "a" }).Arg.Single().Should().Be("a");
            factory.New(new[] { "b" }).Arg.Single().Should().Be("b");
        }
Пример #13
0
        public void GetRequiredService_TwoConstructorsServicesRegisteredForNeither_ShouldThrow()
        {
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            serviceCollection.AddTransient <TwoConstructors>();
            var serviceProvider = serviceCollection.BuildServiceProvider();

            Func <TwoConstructors> factory = () => serviceProvider.GetRequiredService <TwoConstructors>();

            // This is actually checking already built-in behaviour, but illustrates the kind of exception thrown which we want to align with here
            factory.Should().Throw <InvalidOperationException>()
            .WithMessage($"No constructor for type '{typeof(TwoConstructors)}' can be instantiated using services from the service container and default values.");
        }
Пример #14
0
        public void GetRequiredService_FactoryOfOneArgForInterfaceOfRegisteredType_ShouldThrow()
        {
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            serviceCollection.AddTransient <TestServiceOneParam <string> >();
            serviceCollection.AddFactoryFacility();
            var serviceProvider = serviceCollection.BuildServiceProvider();

            Func <IFactory <string, ITestInterfaceOneParam <string> > > factory = () => serviceProvider.GetRequiredService <IFactory <string, ITestInterfaceOneParam <string> > >();

            factory.Should().Throw <InvalidOperationException>()
            .WithMessage($"Unable to resolve service for type '{typeof(ITestInterfaceOneParam<string>)}' while attempting to activate '{typeof(IFactory<string, ITestInterfaceOneParam<string>>)}'.");
        }
Пример #15
0
        public void GetRequiredService_FactoryOfTwoArgsForTypeWithWrongConstructor_ShouldThrow()
        {
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            serviceCollection.AddTransient <WrongConstructor>();
            serviceCollection.AddFactoryFacility();
            var serviceProvider = serviceCollection.BuildServiceProvider();

            Func <IFactory <string, double, WrongConstructor> > factory = () => serviceProvider.GetRequiredService <IFactory <string, double, WrongConstructor> >();

            factory.Should().Throw <InvalidOperationException>()
            .WithMessage($"In order to resolve a parameterised factory for service type '{typeof(WrongConstructor)}', the implementation type '{typeof(WrongConstructor)}' must contain a constructor whose last 2 parameters are assignable from the factory argument types '{typeof(string)}', '{typeof(double)}'.");
        }
Пример #16
0
        public void GetRequiredService_TwoConstructorsServicesRegisteredForOne_ShouldSucceed()
        {
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            serviceCollection.AddTransient <TwoConstructors>();
            serviceCollection.AddSingleton(typeof(string), "a");
            serviceCollection.AddSingleton(typeof(int), 1);
            var serviceProvider = serviceCollection.BuildServiceProvider();

            // This is actually checking already built-in behaviour, but illustrates the kind of exception thrown which we want to align with here
            var instance = serviceProvider.GetRequiredService <TwoConstructors>();

            instance.A.Should().Be("a");
            instance.B.Should().Be(1);
        }
Пример #17
0
        public void New_FactoryOfTwoArgWithMissingService_ShouldThrow()
        {
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            serviceCollection.AddTransient <WrongConstructor>();
            serviceCollection.AddFactoryFacility();
            var serviceProvider = serviceCollection.BuildServiceProvider();

            var factory = serviceProvider.GetRequiredService <IFactory <string, int, WrongConstructor> >();

            Func <WrongConstructor> instance = () => factory.New("a", 1);

            instance.Should().Throw <InvalidOperationException>()
            .WithMessage($"Unable to resolve service for type '{typeof(double)}' while attempting to activate '{typeof(WrongConstructor)}'.");
        }
Пример #18
0
        public void GetRequiredService_TwoConstructorsServicesRegisteredForBoth_ShouldThrow()
        {
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            serviceCollection.AddTransient <TwoConstructors>();
            serviceCollection.AddSingleton(typeof(string), "a");
            serviceCollection.AddSingleton(typeof(int), 1);
            serviceCollection.AddSingleton(typeof(DateTime), 15.June(1980));
            var serviceProvider = serviceCollection.BuildServiceProvider();

            Func <TwoConstructors> factory = () => serviceProvider.GetRequiredService <TwoConstructors>();

            // This is actually checking already built-in behaviour, but illustrates the kind of exception thrown which we want to align with here
            factory.Should().Throw <InvalidOperationException>()
            .WithMessage($@"Unable to activate type '{typeof(TwoConstructors)}'. The following constructors are ambigious:
Void .ctor(System.String, Int32)
Void .ctor(System.DateTime, Int32)");
        }
        public void UsingValueFunction_CreateByFunction_Test2_Dispose()
        {
            var services = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            services.AddTransient <Dummy>();
            using (var serviceProvider = services.BuildServiceProvider()) {
                var u = UsingValue.CreateByServiceProvider <Dummy>(serviceProvider);
                Assert.NotNull(u);

                // first creation
                var d = u.GetValue();
                Assert.NotNull(d);
                Assert.Same(d, u.GetValue());
                Assert.False(d.IsDisposed);

                u.Dispose();
                Assert.Throws <ObjectDisposedException>(() => { u.GetValue(); });
            }
        }
Пример #20
0
        public void New_FactoryOfTwoArgsForRegisteredInterface_ShouldSucceed()
        {
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            serviceCollection.AddTransient <ITestInterfaceTwoParams <string, double>, TestServiceTwoParams <string, double> >();
            serviceCollection.AddFactoryFacility();
            var serviceProvider = serviceCollection.BuildServiceProvider();

            var factory = serviceProvider.GetRequiredService <IFactory <string, double, ITestInterfaceTwoParams <string, double> > >();

            var x = factory.New("a", 1.0);

            x.Arg1.Should().Be("a");
            x.Arg2.Should().Be(1.0);

            var y = factory.New("b", 2.0);

            y.Arg1.Should().Be("b");
            y.Arg2.Should().Be(2.0);
        }
        public void LazyValueFunction_CreateByFunction_Test2_Dispose()
        {
            var services = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            services.AddTransient <Dummy>();
            using (var serviceProvider = services.BuildServiceProvider()) {
                var u = LazyValue.CreateByServiceProvider <Dummy>(serviceProvider);
                Assert.NotNull(u);

                // first creation
                Dummy d = u.GetValue();
                Assert.NotNull(d);
                Assert.Same(d, u.GetValue());

                u.Dispose();

                // dispose twice
                u.Dispose();

                d.DisableDispose();
            }
        }
Пример #22
0
        public void New_FactoryOfThreeArgsForRegisteredType_ShouldSucceed()
        {
            var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            serviceCollection.AddTransient <TestServiceThreeParams>();
            serviceCollection.AddFactoryFacility();
            var serviceProvider = serviceCollection.BuildServiceProvider();

            var factory = serviceProvider.GetRequiredService <IFactory <string, double, bool, TestServiceThreeParams> >();

            var x = factory.New("a", 1.0, false);

            x.Arg1.Should().Be("a");
            x.Arg2.Should().Be(1.0);
            x.Arg3.Should().BeFalse();

            var y = factory.New("b", 2.0, true);

            y.Arg1.Should().Be("b");
            y.Arg2.Should().Be(2.0);
            y.Arg3.Should().BeTrue();
        }
        private static IServiceCollection GetInterceptableServices(IServiceProvider serviceProvider, IServiceCollection services)
        {
            var serviceCollection = new ServiceCollection();

            foreach (var service in services)
            {
                bool isOpneGeneric = service.ServiceType.GetTypeInfo().IsGenericTypeDefinition;
                Func <IServiceProvider, object> factory = _ => Wrap(serviceProvider, service.ServiceType);
                switch (service.Lifetime)
                {
                case ServiceLifetime.Scoped:
                {
                    if (isOpneGeneric)
                    {
                        serviceCollection.AddScoped(service.ServiceType, service.ImplementationType);
                    }
                    else
                    {
                        serviceCollection.AddScoped(service.ServiceType, factory);
                    }
                    break;
                }

                case ServiceLifetime.Singleton:
                {
                    if (isOpneGeneric)
                    {
                        serviceCollection.AddSingleton(service.ServiceType, service.ImplementationType);
                    }
                    else
                    {
                        serviceCollection.AddSingleton(service.ServiceType, factory);
                    }
                    break;
                }

                case ServiceLifetime.Transient:
                {
                    if (isOpneGeneric)
                    {
                        serviceCollection.AddTransient(service.ServiceType, service.ImplementationType);
                    }
                    else
                    {
                        serviceCollection.AddTransient(service.ServiceType, factory);
                    }
                    break;
                }
                }
            }

            foreach (var group in serviceCollection.GroupBy(_ => _.ServiceType))
            {
                if (group.Count() > 1)
                {
                    serviceCollection.AddTransient(typeof(IEnumerable <>).MakeGenericType(group.Key),
                                                   _ =>
                    {
                        IProxyFactory proxyFactory = serviceProvider.GetRequiredService <IProxyFactory>();
                        var proxies = serviceProvider.GetServices(group.Key).Select(target => proxyFactory.CreateProxy(group.Key, target)).ToArray();
                        Array array = Array.CreateInstance(group.Key, proxies.Length);
                        for (int i = 0; i < group.Count(); i++)
                        {
                            array.SetValue(proxies[i], i);
                        }
                        return(array);
                    });
                }
            }
            return(serviceCollection);
        }
Пример #24
0
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // allow cors
            var cors = new EnableCorsAttribute("*", "*", "*");

            config.EnableCors(cors);

            var services = new ServiceCollection();

            services.AddCors();

            services.AddSingleton(_ => new AppDbContext());
            //  services.AddTransient<DbInitializer>();

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            // add config swagger rourte
            config.Routes.MapHttpRoute(
                name: "Swagger",
                routeTemplate: "",
                defaults: null,
                constraints: null,
                handler: new RedirectHandler((message => message.RequestUri.ToString()), "swagger"));

            config.Formatters.Add(new BrowserJsonFormatter());

            // Add Repository
            services.AddTransient(typeof(IUnitOfWork), typeof(UnitOfWork));
            services.AddScoped(typeof(IDataRepository <>), typeof(DataRepository <>));

            // add UserManager
            services.AddTransient <IUserStore <User, Guid>, UserStore>();
            services.AddTransient(typeof(ApplicationUserManager), typeof(ApplicationUserManager));

            // add RoleManager
            services.AddTransient <IRoleStore <Role, Guid>, RoleStore>();
            services.AddTransient(typeof(ApplicationRoleManager), typeof(ApplicationRoleManager));

            //Add Service
            services.AddTransient <INhanVienService, NhanVienService>();
            services.AddTransient <IUserService, UserService>();
            services.AddTransient <IRoleService, RoleService>();
            services.AddTransient <IUserRoleService, UserRoleService>();
            services.AddTransient <IBienTheService, BienTheService>();
            services.AddTransient <IHinhAnhBienTheService, HinhAnhBienTheService>();
            services.AddTransient <IThuocService, ThuocService>();
            services.AddTransient <IBenhService, BenhService>();
            services.AddTransient <IThuocDieuTriService, ThuocDieuTriService>();
            services.AddTransient <ILieuTrinhService, LieuTrinhService>();
            services.AddTransient <ITrieuChungService, TrieuChungService>();
            services.AddTransient <ITrieuChungBenhService, TrieuChungBenhService>();
            services.AddTransient <ICaService, CaService>();
            services.AddTransient <IChungLoaiService, ChungLoaiService>();
            services.AddTransient <IChatLuongService, ChatLuongService>();
            services.AddTransient <IGiongService, GiongService>();
            services.AddTransient <IKhachHangService, KhachHangService>();
            services.AddTransient <ITheoDoiThongTinService, TheoDoiThongTinService>();

            var configMapper = new MapperConfiguration(cfg => {
                cfg.AddProfile <DtoMappingProfile>();
            });

            configMapper.CompileMappings();

            IMapper mapper = configMapper.CreateMapper();

            services.AddSingleton(mapper);


            // Add all controllers as services
            services.AddControllersAsServices(typeof(WebApiConfig).Assembly.GetExportedTypes().Where(t => t.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)));

            var resolver = new MyDependencyResolver(services.BuildServiceProvider());

            config.DependencyResolver = resolver;
        }
Пример #25
0
        static void Main(string[] args)
        {
            ///容器的使用:
            ///            实例化一个容器;
            ///            注册
            ///            获取服务
            IServiceCollection container = new ServiceCollection();

            // IServiceCollection
            container.AddTransient <ITestServiceA, TestServiceA>();     // 瞬时生命周期  每一次获取的对象都是新的对象
            container.AddSingleton <ITestServiceB, TestServiceB>();     // 单例生命周期  在容器中永远只有当前这一个
            container.AddScoped <ITestServiceC, TestServiceC>();        //当前请求作用域内  只有当前这个实例

            container.AddSingleton <ITestServiceD>(new TestServiceD()); // 也是单例生命周期

            ServiceProvider provider = container.BuildServiceProvider();

            ITestServiceA testA  = provider.GetService <ITestServiceA>();
            ITestServiceA testA1 = provider.GetService <ITestServiceA>();

            Console.WriteLine(object.ReferenceEquals(testA, testA1));

            ITestServiceB testB  = provider.GetService <ITestServiceB>();
            ITestServiceB testB1 = provider.GetService <ITestServiceB>();

            Console.WriteLine(object.ReferenceEquals(testB, testB1));

            ITestServiceC testC  = provider.GetService <ITestServiceC>();
            ITestServiceC testC1 = provider.GetService <ITestServiceC>();

            Console.WriteLine(object.ReferenceEquals(testC, testC1));

            IServiceScope scope  = provider.CreateScope();
            ITestServiceC testc3 = provider.GetService <ITestServiceC>();
            var           testc4 = scope.ServiceProvider.GetService <ITestServiceC>();

            Console.WriteLine(object.ReferenceEquals(testc3, testc4));

            ITestServiceD testD  = provider.GetService <ITestServiceD>();
            ITestServiceD testD1 = provider.GetService <ITestServiceD>();

            Console.WriteLine(object.ReferenceEquals(testD, testD1));

            //Console.WriteLine("Hello World!");

            //var user = new
            //{
            //    Id = 11,
            //    Name = "Richard"
            //};
            //Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(user));


            //Console.WriteLine("**************************************");
            //{
            //    SharpSix six = new SharpSix();
            //    People people = new People()
            //    {
            //        Id = 505,
            //        Name = "马尔凯蒂"
            //    };
            //    six.Show(people);
            //}

            //Console.WriteLine("**************************************");
            //{
            //    SharpSeven seven = new SharpSeven();
            //    seven.Show();
            //}
        }
Пример #26
0
        static IServiceProvider CreateContainer(IAzureFunctionsApi azureFunctionsApi, IGitHubApiV3 gitHubApiV3, IGitHubGraphQLApi gitHubGraphQLApi)
        {
            var services = new Microsoft.Extensions.DependencyInjection.ServiceCollection();

            //GitTrends Refit Services
            services.AddSingleton(azureFunctionsApi);
            services.AddSingleton(gitHubApiV3);
            services.AddSingleton(gitHubGraphQLApi);

            //GitTrends Services
            services.AddSingleton <AppInitializationService>();
            services.AddSingleton <AzureFunctionsApiService>();
            services.AddSingleton <BackgroundFetchService>();
            services.AddSingleton <DeepLinkingService>();
            services.AddSingleton <NotificationService, ExtendedNotificationService>();
            services.AddSingleton <GitHubApiV3Service>();
            services.AddSingleton <GitHubApiRepositoriesService>();
            services.AddSingleton <GitHubApiStatusService>();
            services.AddSingleton <GitHubAuthenticationService>();
            services.AddSingleton <GitHubGraphQLApiService>();
            services.AddSingleton <GitHubUserService>();
            services.AddSingleton <GitTrendsStatisticsService>();
            services.AddSingleton <FavIconService>();
            services.AddSingleton <FirstRunService>();
            services.AddSingleton <ImageCachingService>();
            services.AddSingleton <LanguageService>();
            services.AddSingleton <LibrariesService>();
            services.AddSingleton <MediaElementService>();
            services.AddSingleton <ReferringSitesDatabase>();
            services.AddSingleton <RepositoryDatabase>();
            services.AddSingleton <ReviewService>();
            services.AddSingleton <MobileSortingService>();
            services.AddSingleton <SyncfusionService>();
            services.AddSingleton <ThemeService>();
            services.AddSingleton <TrendsChartSettingsService>();

            //GitTrends ViewModels
            services.AddTransient <AboutViewModel>();
            services.AddTransient <OnboardingViewModel>();
            services.AddTransient <ReferringSitesViewModel>();
            services.AddTransient <RepositoryViewModel>();
            services.AddTransient <SettingsViewModel>();
            services.AddTransient <TrendsViewModel>();
            services.AddTransient <WelcomeViewModel>();

            //Mocks
            services.AddSingleton <IAnalyticsService, MockAnalyticsService>();
            services.AddSingleton <IAppInfo, MockAppInfo>();
            services.AddSingleton <IBrowser, MockBrowser>();
            services.AddSingleton <IDeviceNotificationsService, MockDeviceNotificationsService>();
            services.AddSingleton <IFileSystem, MockFileSystem>();
            services.AddSingleton <IEmail, MockEmail>();
            services.AddSingleton <ILauncher, MockLauncher>();
            services.AddSingleton <IMainThread, MockMainThread>();
            services.AddSingleton <INotificationManager, MockNotificationManager>();
            services.AddSingleton <ISecureStorage, MockSecureStorage>();
            services.AddSingleton <IStoreReview, MockStoreReview>();
            services.AddSingleton <IPreferences, MockPreferences>();
            services.AddSingleton <IVersionTracking, MockVersionTracking>();

            return(services.BuildServiceProvider());
        }
        public void EmitsCallSiteBuiltEvent()
        {
            // Arrange
            var serviceCollection   = new ServiceCollection();
            var fakeDisposeCallback = new FakeDisposeCallback();

            serviceCollection.AddSingleton(fakeDisposeCallback);
            serviceCollection.AddTransient <IFakeOuterService, FakeDisposableCallbackOuterService>();
            serviceCollection.AddSingleton <IFakeMultipleService, FakeDisposableCallbackInnerService>();
            serviceCollection.AddSingleton <IFakeMultipleService>(provider => new FakeDisposableCallbackInnerService(fakeDisposeCallback));
            serviceCollection.AddScoped <IFakeMultipleService, FakeDisposableCallbackInnerService>();
            serviceCollection.AddTransient <IFakeMultipleService, FakeDisposableCallbackInnerService>();
            serviceCollection.AddSingleton <IFakeService, FakeDisposableCallbackInnerService>();

            serviceCollection.BuildServiceProvider().GetService <IEnumerable <IFakeOuterService> >();

            var callsiteBuiltEvent = _listener.EventData.Single(e => e.EventName == "CallSiteBuilt");


            Assert.Equal(
                string.Join(Environment.NewLine,
                            "{",
                            "  \"serviceType\": \"System.Collections.Generic.IEnumerable`1[Microsoft.Extensions.DependencyInjection.Specification.Fakes.IFakeOuterService]\",",
                            "  \"kind\": \"IEnumerable\",",
                            "  \"cache\": \"None\",",
                            "  \"itemType\": \"Microsoft.Extensions.DependencyInjection.Specification.Fakes.IFakeOuterService\",",
                            "  \"size\": \"1\",",
                            "  \"items\": [",
                            "    {",
                            "      \"serviceType\": \"Microsoft.Extensions.DependencyInjection.Specification.Fakes.IFakeOuterService\",",
                            "      \"kind\": \"Constructor\",",
                            "      \"cache\": \"Dispose\",",
                            "      \"implementationType\": \"Microsoft.Extensions.DependencyInjection.Specification.Fakes.FakeDisposableCallbackOuterService\",",
                            "      \"arguments\": [",
                            "        {",
                            "          \"serviceType\": \"Microsoft.Extensions.DependencyInjection.Specification.Fakes.IFakeService\",",
                            "          \"kind\": \"Constructor\",",
                            "          \"cache\": \"Root\",",
                            "          \"implementationType\": \"Microsoft.Extensions.DependencyInjection.Specification.Fakes.FakeDisposableCallbackInnerService\",",
                            "          \"arguments\": [",
                            "            {",
                            "              \"serviceType\": \"Microsoft.Extensions.DependencyInjection.Specification.Fakes.FakeDisposeCallback\",",
                            "              \"kind\": \"Constant\",",
                            "              \"cache\": \"None\",",
                            "              \"value\": \"Microsoft.Extensions.DependencyInjection.Specification.Fakes.FakeDisposeCallback\"",
                            "            }",
                            "          ]",
                            "        },",
                            "        {",
                            "          \"serviceType\": \"System.Collections.Generic.IEnumerable`1[Microsoft.Extensions.DependencyInjection.Specification.Fakes.IFakeMultipleService]\",",
                            "          \"kind\": \"IEnumerable\",",
                            "          \"cache\": \"None\",",
                            "          \"itemType\": \"Microsoft.Extensions.DependencyInjection.Specification.Fakes.IFakeMultipleService\",",
                            "          \"size\": \"4\",",
                            "          \"items\": [",
                            "            {",
                            "              \"serviceType\": \"Microsoft.Extensions.DependencyInjection.Specification.Fakes.IFakeMultipleService\",",
                            "              \"kind\": \"Constructor\",",
                            "              \"cache\": \"Root\",",
                            "              \"implementationType\": \"Microsoft.Extensions.DependencyInjection.Specification.Fakes.FakeDisposableCallbackInnerService\",",
                            "              \"arguments\": [",
                            "                {",
                            "                  \"ref\": \"Microsoft.Extensions.DependencyInjection.Specification.Fakes.FakeDisposeCallback\"",
                            "                }",
                            "              ]",
                            "            },",
                            "            {",
                            "              \"serviceType\": \"Microsoft.Extensions.DependencyInjection.Specification.Fakes.IFakeMultipleService\",",
                            "              \"kind\": \"Factory\",",
                            "              \"cache\": \"Root\",",
                            "              \"method\": \"Microsoft.Extensions.DependencyInjection.Specification.Fakes.IFakeMultipleService <EmitsCallSiteBuiltEvent>b__0(System.IServiceProvider)\"",
                            "            },",
                            "            {",
                            "              \"serviceType\": \"Microsoft.Extensions.DependencyInjection.Specification.Fakes.IFakeMultipleService\",",
                            "              \"kind\": \"Constructor\",",
                            "              \"cache\": \"Scope\",",
                            "              \"implementationType\": \"Microsoft.Extensions.DependencyInjection.Specification.Fakes.FakeDisposableCallbackInnerService\",",
                            "              \"arguments\": [",
                            "                {",
                            "                  \"ref\": \"Microsoft.Extensions.DependencyInjection.Specification.Fakes.FakeDisposeCallback\"",
                            "                }",
                            "              ]",
                            "            },",
                            "            {",
                            "              \"serviceType\": \"Microsoft.Extensions.DependencyInjection.Specification.Fakes.IFakeMultipleService\",",
                            "              \"kind\": \"Constructor\",",
                            "              \"cache\": \"Dispose\",",
                            "              \"implementationType\": \"Microsoft.Extensions.DependencyInjection.Specification.Fakes.FakeDisposableCallbackInnerService\",",
                            "              \"arguments\": [",
                            "                {",
                            "                  \"ref\": \"Microsoft.Extensions.DependencyInjection.Specification.Fakes.FakeDisposeCallback\"",
                            "                }",
                            "              ]",
                            "            }",
                            "          ]",
                            "        },",
                            "        {",
                            "          \"ref\": \"Microsoft.Extensions.DependencyInjection.Specification.Fakes.FakeDisposeCallback\"",
                            "        }",
                            "      ]",
                            "    }",
                            "  ]",
                            "}"),
                JObject.Parse(GetProperty <string>(callsiteBuiltEvent, "callSite")).ToString());

            Assert.Equal("System.Collections.Generic.IEnumerable`1[Microsoft.Extensions.DependencyInjection.Specification.Fakes.IFakeOuterService]", GetProperty <string>(callsiteBuiltEvent, "serviceType"));
            Assert.Equal(0, GetProperty <int>(callsiteBuiltEvent, "chunkIndex"));
            Assert.Equal(1, GetProperty <int>(callsiteBuiltEvent, "chunkCount"));
            Assert.Equal(1, callsiteBuiltEvent.EventId);
        }