我正在努力做到这一点:
builder.RegisterInstance(EngineFactory.Instance).SingleInstance().ExternallyOwned();
builder.Register(c =>
{
EngineFactory engineFactory = DependencyResolver.Current.GetService<EngineFactory>();
//EngineFactory engineFactory = c.Resolve<EngineFactory>();
IEngineService engineService = engineFactory.GetService();
return engineService;
}).InstancePerRequest().As<IEngineService>();
我收到了错误:
No scope with a Tag matching 'AutofacWebRequest' is visible from the scope in which the instance was requested.
This generally indicates that a component registered as per-HTTP request is being requested by a SingleInstance() component (or a similar scenario.)
Under the web integration always request dependencies from the DependencyResolver.Current or ILifetimeScopeProvider.RequestLifetime, never from the container itself.
为了清楚起见,我希望EngineFactory是一个单例(外部创建),IEngineService是一个Per(web)请求实例。
在控制器属性注入IEngineService时发生错误。
我不明白我做错了什么......
答案 0 :(得分:0)
您报告的代码是正确的,AFAICT。
特别是:
// this is ok.
builder.RegisterInstance(EngineFactory.Instance).SingleInstance().ExternallyOwned();
// you can use c.Resolve<EngineFactory>() and probably you should,
// but really, is the same as your code
builder.Register(c => c.Resolve<EngineFactory>().GetService())
.InstancePerRequest().AsImplementedInterfaces();
您收到的错误消息是您将IEngineService解析与Http Request绑定。在Autofac中,这是通过标记范围来管理的,即通过负责对象跟踪和处理的容器。标记范围只是具有名称的范围。
使用InstancePerRequest时,Autofac会搜索名为AutofacWebRequest的作用域,该作用域由Autofac / Asp.Net集成自动创建和处理,这可能无法正确设置。
您的问题几乎可以肯定是Autofac / Asp.Net集成配置。
因此,请参阅guide on the website,如有问题请再次询问。
最后一件事:如果你还没有,请阅读Autofac Lifetime Primer。如果你使用Autofac,它就是纯金。
编辑:你是不是在Asp.Net Core?如果是这种情况,here您可以找到不使用InstancePerRequest的注释。