如何将 DBContext 注入 HTTPModule

How can I inject DBContext to HTTPModule

我在创建使用 Entity Framework.
的 http 模块时遇到 DBContext 问题 我想将 DBContext 注入 httpmodule 就像在 constructor.
中注入依赖一样 有什么解决办法吗?

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);
    ...
        }
    }

我想要的是将 dbcontext 注入到 httpmodule 中,例如:

    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);
    ...
        }
    }
    

我使用 Simple Injector 找到了这个问题的简单解决方案。

安装了 3 个 NuGet 包。 (Microsoft.Web.Infrastructure, SimpleInjector, SimpleInjector.Integration.Web)

并为 MyDBContext

创建了界面

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;
}

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; }
}

MyHTTPModule

private IDBContext DBContext;
public MyHTTPModule()
{
    DBContext = Global.Container.GetInstance<IDBContext>();
}