似乎很疯狂,这样的事情让我如此头疼。但这里是:
如何为非 Controller 类使用 net core 的内置依赖注入(inject)?请提供包含实例化的示例。
谢谢。
最佳答案
您可以轻松定义 静态类 具有如下属性:
public static class StaticServiceProvider
{
public static IServiceProvider Provider { get; set; }
}
定义类后你必须范围 Startup.ConfigureServices 方法中的服务:
public void ConfigureServices(IServiceCollection services)
{
//TODO: ...
services.AddScoped<IUnitOfWork, HttpUnitOfWork>();
services.AddSingleton<ISomeInterface, ISomeImplementation>();
}
然后在启动时的 Startup.Configure 方法中,您可以 设置 提供者作为静态类属性:
public void Configure(IApplicationBuilder app, ...)
{
StaticServiceProvider.Provider = app.ApplicationServices;
//TODO: ...
}
现在您几乎可以轻松调用 StaticServiceProvider.Provider.GetService 方法 无处不在在您的应用程序中:
var unitOfWork = (IUnitOfWork)StaticServiceProvider.Provider.GetService(typeof(IUnitOfWork));
关于dependency-injection - 非 Controller 的网络核心依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41614194/