我需要在global.asax中启动应用程序时执行一些一次性代码。我已经启动autofac并运行了大量注册,但问题是我无法弄清楚如何解析或注入依赖到我的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; }
}
答案 0 :(得分:2)
这让我最终解决了我的依赖关系。
using(var scope = container.BeginLifetimeScope("AutofacWebRequest"))
{
scope.Resolve<SecurityConfig>().RegisterActivities();
}