ZeroOne
ZeroOne

Reputation: 791

Unity Entity Framework within ASP.NET WebAPI 2

I have a very weird problem with Unity here. I have the following:

public class UnityConfig
{

    public static void RegisterTypes(IUnityContainer container)
        container.RegisterType<IDBContext, MyDbContext>(new PerThreadLifetimeManager());
        container.RegisterType<IUserDbContext>(new PerThreadLifetimeManager(), new InjectionFactory(c =>
        {
            var tenantConnectionString = c.Resolve<ITenantConnectionResolver>().ResolveConnectionString();
            return new UserDbContext(tenantConnectionString);
        }));
    }
}

and then in the WebApiConfig.cs file within the Reigster method:

var container = new UnityContainer();    
UnityConfig.RegisterTypes(container);
config.DependencyResolver = new UnityResolver(container);

Basically, what I want to happen in the above code is on every request to the API, I want Unity to new up a UserDbContext based on the user (multi-tenant kind of environment). Now the TenantConnectionResolver is responsible for figuring out the Connection String and then I use that connection string to new up UserDbContext.

Also note (not shown above) that TenantConnectionResolver takes an IDbConext in its constructor because I need it to figure out the connection string based on user information in that database.

But for some reason, the code within the InjectionFactory runs at random times. For example, I call //mysite.com/controller/action/1 repetitively from a browser, the code in the InjectionFactory will occasionally run but not on each request.

Am I incorrectly configuring Unity? Has anybody encountered anything similar to this?

Thanks in advance

Upvotes: 1

Views: 533

Answers (1)

Najkin
Najkin

Reputation: 932

The problem is very likely related to the LifetimeManager you are using. PerThreadLifetimeManager is not adapted in a web context, as threads are pooled and will serve multiple requests in sequence.

PerRequestLifetimeManager is probably what you want to use.

Upvotes: 1

Related Questions