每个应用程序启动Autofac注册行动 [英] Register action with Autofac per application start
问题描述
我使用MVC与Autofac。我想注册一个每个应用程序开始运行一次行动。我想实现某事。像这样的:
I'm using MVC with Autofac. I'd like to register action that runs once per application start. I'd like to achieve sth. like this:
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>();
有可能执行这样的操作?
It is possible to perform such an action?
我知道我可以使用内置容器( VAR容器= builder.Build();
&LT; - 解决人工服务),但也许有更多的优雅的解决方案像上面。
I know I could use built container (var container = builder.Build();
<-- resolve manually services) but maybe there is more "elegant" solution like that above.
推荐答案
你所寻找的是的可启动组件在Autofac的支持。
What you are looking for is the Startable Components support in Autofac.
您需要执行 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将完成剩下的运行中的开始
方法,一旦容器时建
and Autofac will do the rest the run the Start
method once when the container is built.
这篇关于每个应用程序启动Autofac注册行动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!