I have a problem with DBContext
while creating httpmodule that uses Entity Framework
.
I'd like to inject DBContext
into the httpmodule
like injecting dependency in constructor
.
Is there any solution for me?
in MyHTTPModule
public class MyHTTPModule: IHttpModule { ... public void OnBeginRequest(object sender, EventArgs e) { HttpApplication Application = (HttpApplication)sender; HttpContext Context = Application.Context; string filepath= Context.Request.FilePath; MyDBContext db = new MyDBContext(); var file = db.file.FirstOrDefault(r => r.filename == filepath); ... } }
What I want is injecting dbcontext into httpmodule like:
public class MyHTTPModule: IHttpModule { private MyDBContext db; public MyHTTPModule(MyDBContext dbcontext) { db = dbcontext; } ... public void OnBeginRequest(object sender, EventArgs e) { HttpApplication Application = (HttpApplication)sender; HttpContext Context = Application.Context; string filepath= Context.Request.FilePath; var file = db.file.FirstOrDefault(r => r.filename == filepath); ... } }
I found simple solution for this problem using Simple Injector.
Installed 3 NuGet packages. (Microsoft.Web.Infrastructure, SimpleInjector, SimpleInjector.Integration.Web)
and created interface for MyDBContext
in Global.asax.cs
private static Container container;
public static Container Container
{
get { return container ?? (container = RegisterAndVerifyContainer()); }
}
private static Container RegisterAndVerifyContainer()
{
var container = new Container();
container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();
container.Register<IDBContext, MyDBContext>(Lifestyle.Singleton);
container.Verify();
return container;
}
in MyDBContext
public partial class MyDBContext: DbContext, IDBContext
{
public MyDBContext() : base("name=MyDBContext")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<file> file{ get; set; }
}
public interface IDBContext : IDisposable
{
DbSet<file> file { get; set; }
}
in MyHTTPModule
private IDBContext DBContext;
public MyHTTPModule()
{
DBContext = Global.Container.GetInstance<IDBContext>();
}