I am using Castle Windsor as my IoC container and I registered it as a DependencyResolver to let the MVC framework know about it.

With the Entity Framework I have this DbContext:

public class MyDbContext : DbContext
    public DbSet<User> Users { get; set; }

In Castle Windsor it is registered as per web request:

    Component.For<DbContext, MyDbContext>()

Because I don't have control over creating the MyMembershipProvider object, this object is created once per web application so it is not possible to inject DbContext directly, because it will be disposed when the web request ends.

I wrote this as a solution:

public interface IDoInContext<TContext>
    void DoInContext(Action<TContext> action);

public class DoInMyDbContext : IDoInContext<MyDbContext>
    IKernel _kernel;

    public DoInMyDbContext(IKernel kernel)
        _kernel = kernel;

    public void DoInContext(Action<MyDbContext> action)
        var context = _kernel.Resolve<MyDbContext>();

And I registered like this:


Now I can create a MyMembershipProvider which will be able to interact with the current and correct DbContext every time it needs:

public class MyMembershipProvider : MembershipProvider
    IDoInContext<MyContext> db;

    public MyMembershipProvider()
        : this(DependencyResolver.Current.GetService<IDoInContext<MyContext>>())
    { }

    public MyMembershipProvider(IDoInContext<MyContext> db)
        this.db = db;

    public override bool ValidateUser(string username, string password)
        bool result = false;
        db.DoInContext(x => {
            var encodedPassword = encodePassword(password);
            result = x.Users.Any(y => y.Login == username && 
                                      y.Password == encodedPassword);
        return result;


It seems to be stable and I can't see any memory leaks or any other problems. What do you think? Is the DoInContext(Action<TContext> action) thing any sort of pattern, anti-pattern or bad practice?

  • \$\begingroup\$ Why exactly do you say the MyDbContext cannot be injected directly? I'm trying to see if I understand what you mean, so I could help you out. \$\endgroup\$ – IEatBagels Oct 7 '14 at 12:36
  • \$\begingroup\$ Because my code is not creating instance of the provider. Provider must have constructor without parameters and this constructor is used by .NET. So I cannot inject any constructor parameters. \$\endgroup\$ – Lukas Pirkl Jan 2 '15 at 8:51

The preferred method of doing this is to use a factory dependency that creates the DbContext for you. So instead of the DbContext as the dependency you have a ContextFactory as the dependency and its consumers can get and manage a local DbContext by calling contextFactory.CreateContext();

If you insist on having your context injected directly, I believe it would be much better to have your MembershipProvider be registered per web request (even though you don't have control over creating it, you still have to register it right?). It shouldn't be a bottleneck. From a design and testing perspective this is much preferred to having a hard dependency on a service locator. How will you test the class by itself? Would you be incorporating your service locator into your tests?


Using delegated execution in context is acceptable.

The other question is how to use MembershipProvider in an application using an IoC, while it’s not convenient to use MemberhipProvider in IoC context in a testable manner, using constructor injection, for example. You would need to incorporate a service locator in tests, as noted in another answer.

If you implement your own authentication database, is it convenient to implement a custom interface, then adapt it to MembershipProvider? It’s not uncommon for an application to use features not provided by MembershipProvider, such as a user locking strategy. Some features are probably completely useless for an application. One example would be the standard authentication controls in asp.net classic, since it's an asp.net-mvc application. So there will be probably many methods with empty implementation. It would be using a leaky abstraction then.

Provider model is designed to reuse the standard implementations for applications, which could possibly have unlimited customized deployments, such as a CMS, with a bias towards the standard implementation based on MS SQL Server, so the following questions arise:

  1. Can I use the other implementations of MembershipProvider in my application?
  2. Is my implementation reusable, can it be used by other applications?
  3. Will I ever use full functionality for which the MembershipProvider was designed, such as the standard asp.net based UI for administering users and groups?
  4. Will I use the standard user controls such as LoginControl from the asp.net classic?
  5. If I implement my own MembershipProvider, can I somehow avoid violation of encapsulation, when accessing the same database from my application code that is used in my implementation of MembershipProvider?

If it’s an application with single deployment, then the most probable answer would be 'no'. Why to use MembershipProvider at all then?

If you use it just to be able to use the standard attributes on the mvc controller methods, it’s easier to implement your own custom attribute and register it with IoC and filter pipeline with mvc: Dependency Injection in ASP.NET MVC: Filters


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.