[英]ServiceLocator with Autofac in asp.net core 3.1
我正在开发一个 asp.net core 3.1 webapi 应用程序,我使用 Autofac 作为 DI 容器。 对于一种特殊情况,我不能使用 ConstructorInjection、propertyinjection 或 methodinjection。 我唯一的方法是在 Autofac 的支持下实现一种 ServiceLocator 模式。
*我知道服务定位器是一种反模式,但只有当它是唯一的机会时我才会使用它*
说,我创建了一个小静态类:
public static class ServiceLocator
{
private static XXXX Resolver;
public static T Resolve<T>()
{
return Resolver.Resolve<T>();
}
public static void SetCurrentResolver(XXXX resolver)
{
Resolver = resolver;
}
}
我在 Resolver 属性的类型上写了 XXXX,因为我不知道要使用哪个 Autofac 类。 Startup.cs的Configure方法中会调用SetCurrentResolver方法
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILifetimeScope serviceProvider)
{
//OTHER STUFF NOT RELATED HERE
ServiceLocator.SetCurrentResolver(serviceProvider);
}
我试图传递 ILifetimeScope 的实例,但是当我稍后在服务定位器中使用它时,它将被处理,然后不起作用。 我想传递一个 IContainer 对象,但我无法在 Startup.cs 中检索实例(无论是在Configure方法中还是在ConfigureContainer 中)
我报告 ConfigureContainer 方法完成
public void ConfigureContainer(ContainerBuilder builder)
{
//first register the dependency for WebApi Project
builder.RegisterType<HttpContextUserService>().As<IUserService>().SingleInstance();
//and then register the dependency for all other project
var appConfiguration = new AppConfiguration();
Configuration.GetSection("Application").Bind(appConfiguration);
builder.RegisterInstance(appConfiguration).SingleInstance();
builder.RegisterModule(new DependencyInjectionBootstrapper(appConfiguration));
}
任何人都可以帮我解决这个问题吗?
谢谢
如果您查看示例,这实际上在 Autofac 文档中得到了回答。
这是相关的位。
public class Startup
{
public Startup(IHostingEnvironment env)
{
// Body omitted for brevity.
}
public ILifetimeScope AutofacContainer { get; private set; }
public void ConfigureServices(IServiceCollection services)
{
// Body omitted for brevity.
}
public void ConfigureContainer(ContainerBuilder builder)
{
// Body omitted for brevity.
}
public void Configure(IApplicationBuilder app)
{
// If, for some reason, you need a reference to the built container, you
// can use the convenience extension method GetAutofacRoot.
// THIS IS WHERE YOU'D SET YOUR SERVICE LOCATOR.
this.AutofacContainer = app.ApplicationServices.GetAutofacRoot();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.