Reputation: 4328
I need to execute some one-time code on start of my application in the global.asax. I've already got autofac up and running with numerous registrations but the problem is that I can't figure out how to resolve or inject a dependency into SecurityConfig.RegisterActivities() that's inside my global.asax.
I tried manually resolving the dependency myself in global.asax using the autofac container but it threw the exception "No scope with a Tag matching 'AutofacWebRequest' is visible from the scope in which the instance was requested."
How do I get this dependency into that class?
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; }
}
Upvotes: 4
Views: 6491
Reputation: 4328
This allowed me to resolve my dependencies finally.
using(var scope = container.BeginLifetimeScope("AutofacWebRequest"))
{
scope.Resolve<SecurityConfig>().RegisterActivities();
}
Upvotes: 2