问题描述
我使用autofac在一个asp.net MVC和的WebAPI项目。
I'm using autofac in an asp.net mvc and webapi project.
在配置我这样做:
var builder = new ContainerBuilder();
builder.Register(x => NHibernateConfigurator.BuildSessionFactory()).SingleInstance();
builder.Register(x => x.Resolve<ISessionFactory>().OpenSession()).InstancePerHttpRequest();
builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource());
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
现在的问题是,在API控制器,如果我通过建筑工注入的ISession也叫
Now the problem is that in an api controller if I inject ISession via the constructer and also call
DependencyResolver.Current.GetService<ISession>()
它会返回2不同的实例。
it will return 2 different instances.
我猜这个问题是因为这些2行:
I'm guessing the problem is because of these 2 lines :
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
但我怎么可以让它返回同一个实例?
But how can I make it return the same instance ?
编辑:
只是要更清楚 - 我期待的ISession每Htt的prequest相同的实例。现在,我在同样的要求得到不同的实例。
Just to be more clear - I'm expecting the same instance of ISession per HttpRequest. Right now I'm getting different instances on the same request.
感谢
推荐答案
好吧,我想我找到了答案 - 它不能这样做..至少不符合DependencyResolver
Ok, I think I found the answer - it can't be done .. at least not with DependencyResolver.
我做了什么,它说在评论中,添加IComponentContext的构造和使用,解决我所需要的。
I did what it said in the comments, added IComponentContext to the constructor and used that to resolve what I needed.
这似乎是工作。谢谢你。
It seems to be working. Thanks.
这篇关于Autofac在asp.net的MVC Web API返回不同的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!