Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7702131
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T23:09:24+00:00 2026-05-31T23:09:24+00:00

Using EF DbContext wrapped in interface(s), dependency injected per web request, to make sure

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T23:09:25+00:00Added an answer on May 31, 2026 at 11:09 pm

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am building an ASP.NET MVC web application using entity framework DbContext using the
I am having trouble sending a SQL statement through a DbContext using context.Database.ExecuteSqlCommand() .
I am trying to reproduce the same behavior as EntityObject using CTP5 DBContext for
I'm using EntityFramework v4.3.1 and building my model via code by inheriting from DbContext
Using VS2008, C#, .Net 2 and Winforms how can I make a regular Button
Using JDeveloper , I started developing a set of web pages for a project
I'm using LINQ-to-Entities. Using the following query: var x = from u in context.Users
I'm using the DbContext class within code that I am creating that is based
I am reading this E.F. Team Blog's this series http://blogs.msdn.com/b/adonet/archive/2011/01/27/using-dbcontext-in-ef-feature-ctp5-part-1-introduction-and-model.aspx At many places i
I am implementing WCF Data Services using a DbContext and POCO entities. I am

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.