I am using Castle Windsor as my IoC and I registered it as DependencyResolver to let MVC framework know about it.
With 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:
container.Register(
Component.For<DbContext, MyDbContext>()
.ImplementedBy<MyDbContext>()
.LifestylePerWebRequest()
);
Because I don't have a control under creating 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 web request ends. So I wrote this little think:
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>();
action(context);
_kernel.ReleaseComponent(context);
}
}
And I registered it this way:
container.Register(
Component.For<IDoInContext<MyDbContext>>()
.ImplementedBy<DoInMyDbContext>()
.LifestyleSingleton()
);
So now I can create MyMembershipProvider which will be able to interact with current and correct DbContext everytime it needs.
public class MyMembershipProvider : MembershipProvider
{
IDoInContext<MyContext> db;
public MyMembershipProvider()
: this(DependencyResolver.Current.GetService<IDoInContext<MyContext>>())
{ }
public MyMembershipProvider(IDoInContext<PastvinyContext> 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?