猿问

使用 Asp.Net Core DI 的服务的配置范围

是否可以在 Asp.Net Core 中为默认 DI 设置注入范围?我的意思是例如:


services.AddSingleton<IUser, UserService>

services.AddSingleton<IUser, UserService>

对于第二个配置,以某种方式指定它应该只注入到 HomeController。不像第一个应该注入所有其他人。是否可以使用默认 DI?


紫衣仙女
浏览 214回答 2
2回答

杨魅力

我的直觉是这可能是您想要实现的目标,或者可能是更好的方法,并且您可能将 User 与 UserService 混为一谈。当您有同一个接口的多个实现时,DI 会将它们添加到一个集合中,因此可以使用typeof.// In Startup.cspublic void ConfigureServices(IServiceCollection services){&nbsp; &nbsp; services.AddScoped(IUserService, UserServiceA);&nbsp; &nbsp; services.AddScoped(IUserService, UserServiceB);&nbsp; &nbsp; services.AddScoped(IUserService, UserServiceC);}// Any class that uses the service(s)public class Consumer{&nbsp; &nbsp; private readonly IEnumerable<IUserService> _myServices;&nbsp; &nbsp; public Consumer(IEnumerable<IUserService> myServices)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; _myServices = myServices;&nbsp; &nbsp; }&nbsp; &nbsp; public UserServiceA()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var userServiceA = _myServices.FirstOrDefault(t => t.GetType() == typeof(UserServiceA));&nbsp; &nbsp; &nbsp; &nbsp; userServiceA.DoTheThing();&nbsp; &nbsp; }&nbsp; &nbsp; public UserServiceB()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var userServiceB = _myServices.FirstOrDefault(t => t.GetType() == typeof(UserServiceB));&nbsp; &nbsp; &nbsp; &nbsp; userServiceB.DoTheThing();&nbsp; &nbsp; }&nbsp; &nbsp; public UseServiceC()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var userServiceC = _myServices.FirstOrDefault(t => t.GetType() == typeof(UserServiceC));&nbsp; &nbsp; &nbsp; &nbsp; userServiceC.DoTheThing();&nbsp; &nbsp; }}
随时随地看视频慕课网APP
我要回答