使用autofac在global.asax中解析或注入依赖项
本文关键字:注入 依赖 autofac global asax 使用 | 更新日期: 2023-09-27 18:26:55
我需要在global.asax中启动我的应用程序时执行一些一次性代码。我已经启动并运行了许多注册,但问题是我不知道如何解决或向global.asax.中的SecurityConfig.RegisterActivities()注入依赖项
我尝试使用autofac容器在global.asax中手动解析依赖项,但它抛出了异常"从请求实例的作用域中看不到标记匹配"AutofacWebRequest"的作用域。"
如何将此依赖项导入该类?
protected void Application_Start()
{
var builder = new ContainerBuilder();
DependencyRegistrar dr = new DependencyRegistrar();
dr.Register(builder);
new SecurityConfig().RegisterActivities(); // this needs injecting into or resolving of IServiceManager instance
}
public class DependencyRegistrar
{
public virtual IContainer Register(ContainerBuilder builder)
{
builder.RegisterType<ServiceManager>().As<IServiceManager>().InstancePerHttpRequest();
builder.RegisterType<SecurityConfig>().AsSelf().PropertiesAutowired().InstancePerDependency();
}
}
public class SecurityConfig
{
public void RegisterActivities()
{
ServiceManager.DoSomething();
}
public IServiceManager ServiceManager { get; set; }
}
这让我最终解决了依赖关系。
using(var scope = container.BeginLifetimeScope("AutofacWebRequest"))
{
scope.Resolve<SecurityConfig>().RegisterActivities();
}