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 GetRequiredService_FactoryOfOneArgForTypeRegisteredAsNonTransient_ShouldThrow() { var serviceCollection = new Microsoft.Extensions.DependencyInjection.ServiceCollection(); serviceCollection.AddScoped <TestServiceOneParam <string> >(); serviceCollection.AddFactoryFacility(); var serviceProvider = serviceCollection.BuildServiceProvider(); Func <IFactory <string, TestServiceOneParam <string> > > factory = () => serviceProvider.GetRequiredService <IFactory <string, TestServiceOneParam <string> > >(); factory.Should().Throw <InvalidOperationException>() .WithMessage($"In order to resolve a parameterised factory for service type '{typeof(TestServiceOneParam<string>)}', the implementation type '{typeof(TestServiceOneParam<string>)}' must be registered with Transient lifestyle."); }
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(); //} }
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; }
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); }
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); }