在代码优先的实体类中依赖注入 [英] Dependency injection in entity classes with code first

查看:291
本文介绍了在代码优先的实体类中依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出一种在实体框架代码中处理依赖注入的方法。



我偶然发现了一个文章使用ObjectStateManager虽然我不认为它可以在代码中首先,所以我正在寻找类似的东西,我可以将一个对象注入(属性注入)到一个新创建/获取的实体中,或者可能有不同的方式?



我是使用Autofac作为di容器

解决方案

你可以这样做DI

  public class YourContext:DbContext 
{
protected ObjectContext ObjectContext
{
get
{
return(( IObjectContextAdapter)本).ObjectContext;
}
}

public YourContext(string connectionString):base(connectionString)
{
ObjectContext.ObjectMaterialized + = ObjectMaterialized;
}

void ObjectMaterialized(object sender,ObjectMaterializedEventArgs e)
{
//在这里使用e.Entity

}
}


I'm trying to figure out a way to handle dependency injection in entity framework code first.

I stumbled upon an article that uses ObjectStateManager though I don't think it's available in code first, so I'm looking for something similar where I could inject (property injection) an object into a newly created/fetched entity, or maybe there's a different way?

I'm using Autofac as the di container

解决方案

You can do DI like this

 public class YourContext : DbContext
 {
    protected ObjectContext ObjectContext
    {
        get
        {
            return ((IObjectContextAdapter)this).ObjectContext;
        }
    }

    public YourContext(string connectionString):base(connectionString)
    {
        ObjectContext.ObjectMaterialized += ObjectMaterialized;
    }

    void ObjectMaterialized(object sender, ObjectMaterializedEventArgs e)
    {
        // do property injection here using e.Entity
    }
 }

这篇关于在代码优先的实体类中依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆