Autofac returns another instance in asp.net mvc web api

I am using autofac in an asp.net mvc and webapi project.

In the configuration, I do this:

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);

Now the problem is that in the api controller, if I implement ISession through the constructor, and also call

DependencyResolver.Current.GetService<ISession>() 

it will return 2 different instances.

I assume the problem is with these two lines:

DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

But how can I get him to return the same instance?

Edit:

Just to be more clear - I expect the same instance of ISession on HttpRequest. Now I get different instances on the same request.

thank

+1
source share
1 answer

, , - .. , DependencyResolver.

ASP.NET 4 Apar RC + Autofac

, , IComponentContext , , .

, . .

+1

Source: https://habr.com/ru/post/1530142/


All Articles