我正在使用MVC和Autofac.我想注册每个应用程序启动运行一次的操作.我想要实现某事.像这样:
public class SomeModule : IOnceRunnable
{
private IService service;
public SomeModule(IService service)
{
this.service = service;
}
public void Action()
{
// this action would be called once on application start
}
}
containerBuilder.RegisterOnceRunnable<SomeModule>();
可以执行这样的动作吗?
我知道我可以使用构建的容器(var container = builder.Build();< – 解决手动服务)但也许有更多“优雅”的解决方案,如上所述.
最佳答案 您正在寻找的是Autofac中的
Startable Components支持.
您需要实现Autofac.IStartable接口:
public class SomeModule : Autofac.IStartable
{
private IService service;
public SomeModule(IService service)
{
this.service = service;
}
public void Start()
{
// this action would be called once on application start
}
}
您还需要将您的类型注册为IStartable:
builder
.RegisterType<SomeModule>()
.As<IStartable>()
.SingleInstance();
当构建容器时,Autofac将完成其余的运行Start方法.