Question

Using EF DbContext wrapped in interface(s), dependency injected per web request, to make sure the entire request deals with the same context. Also have a custom RoleProvider which consumes the DbContext by interface to customize authorization services.

Until now I have been using service locator pattern to resolve the DbContext instance in the custom RoleProvider's no-arg constructor. This has caused some minor issues because the RoleProvider is singletonish, so it may hold onto a DbContext indefinitely whereas other requests may want to dispose of it during Application_EndRequest.

I now have a solution based on this, though using a different ioc container than windsor. I can use DI to new up a custom RoleProvider instance for each http request.

My question is, should I?

Having an open DbContext hanging off the RoleProvider seems wasteful. On the other hand, I know every MVC AuthorizeAttribute hits the RoleProvider (if it has a non-null Roles property, which most of ours do) so I suppose it could be useful to already have a DbContext in waiting.

The alternative would be to inject a different DbContext for the RoleProvider that is not per web request. This way the DbContexts that live only for the web request can be disposed at the end, without affecting the singletony RoleProvider.

Is either approach better, and why?

Update after comments

Steven, this is essentially what I did. The only difference is that I don't take a dependency on System.Web.Mvc.DependencyResolver. Instead, I basically have the same exact thing in my own project, just named differently:

public interface IInjectDependencies
{
    object GetService(Type serviceType);
    IEnumerable<object> GetServices(Type serviceType);
}

public class DependencyInjector
{
    public static void SetInjector(IInjectDependencies injector)
    {
        // ...
    }

    public static IInjectDependencies Current
    {
        get
        {
           // ...
        }
    }
}

These classes are part of the project's core API, and are in a different project than MVC. This way, that other project (along with the domain project) don't need to take a dependency on System.Web.Mvc in order to compile against its DependencyResolver.

Given that framework, swapping out Unity with SimpleInjector has been painless so far. Here is what the multipurpose singleton RoleProvider setup looks like:

public class InjectedRoleProvider : RoleProvider
{
    private static IInjectDependencies Injector 
        { get { return DependencyInjector.Current; } }

    private static RoleProvider Provider 
        { get { return Injector.GetService<RoleProvider>(); } }

    private static T WithProvider<T>(Func<RoleProvider, T> f)
    {
        return f(Provider);
    }

    private static void WithProvider(Action<RoleProvider> f)
    {
        f(Provider);
    }

    public override string[] GetRolesForUser(string username)
    {
        return WithProvider(p => p.GetRolesForUser(username));
    }

    // rest of RoleProvider overrides invoke WithProvider(lambda)
}

Web.config:

<roleManager enabled="true" defaultProvider="InjectedRoleProvider">
    <providers>
        <clear />
        <add name="InjectedRoleProvider" type="MyApp.InjectedRoleProvider" />
    </providers>
</roleManager>

IoC Container:

Container.RegisterPerWebRequest<RoleProvider, CustomRoleProvider>();

As for CUD, there is only 1 method implemented in my CustomRoleProvider:

public override string[] GetRolesForUser(string userName)

This is the only method used by MVC's AuthorizeAttribute (and IPrincipal.IsInRole), and from all other methods, I simply

throw new NotSupportedException("Only GetRolesForUser is implemented.");

Since there are no role CUD ops on the provider, I am not worried about transactions.

Was it helpful?

Solution

Take a look at the Griffin.MvcContrib project. It contains a MembershipProvider and RoleProvider implementation that make use of the MVC DependencyResolver.

You can configure the RoleProvider like this:

<roleManager enabled="true" defaultProvider="MvcRoleManager">
  <providers>
    <clear />
    <add name="MvcRoleManager" 
      type="Griffin.MvcContrib.Providers.Roles.RoleProvider, Griffin.MvcContrib"
    />
  </providers>
</roleManager>

It makes use of the System.Web.MVC DependencyResolver class so you need to configure an IDependencyResolver implementation for the DI container you are using. With Simple Injector (and the SimpleInjector.MVC3 integration NuGet package), you need the following configuration in your Application_Start event:

container.RegisterAsMvcDependencyResolver();

The Griffin.MvcContrib.Providers.Roles.RoleProvider takes a dependency on a IRoleRepository which is defined in the same assembly. Instead of having to implement a complete role provider you can now just implement the IRoleRepository and register it in your container:

container.Register<IRoleRepository, MyOwnRoleRepository>();

You can find this project here on NuGet.

UPDATE

And now let's answer the question:

The Griffin.MvcContrib RoleProvider will be singleton, and the question now moves to the IRoleRepository and its dependencies, but the question indeed still remains.

If all you do is read from the Role Provider (never update the database); in that case it doesn't matter which lifetime you choose, as long as you don't reuse the same DbContext over threads.

However, when you do use the role provider to update the database, things get different. In that case I would give it its own context, and let it explicitly commit it after each operation. Because if you don't, who is going to commit those changes? When running in the context of a Command Handler (and especially a TransactionCommandHandlerDecorator), the operation will be committed after the command succeeded and rolled back when the command failed. Perhaps it is fine to roll that change back when the command failed. But when the role provider runs outside the context of a command handler, who is going to commit it? I'm sure you will be able to solve this, but I believe you end up with a system that is hard to grasp and it will dazzle other developers who try to find out why those changes didn't commit.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top