【问题标题】:Resolve EF dynamic proxy in Autofac解析 Autofac 中的 EF 动态代理
【发布时间】:2019-03-08 07:44:17
【问题描述】:

我正在使用 Entity Framework 并注册了一些类型以在工厂类中使用。

使用Keyed 执行注册,如下所示:

builder.RegisterType<CreateTypeAStrategy>().Keyed<ICreateWorkItemsStrategy>(typeof(TypeA));

这里TypeA是一个实体。

我是这样解决的(动作类型为 TypeA):

var strategy = scope.ResolveKeyed<ICreateWorkItemsStrategy>(action.GetType(), new TypedParameter(action.GetType(), action));

我得到了预期的ComponentNotRegisteredException,因为proxy 没有注册,只有具体的类。

接口和策略声明如下:

public interface ICreateWorkItemsStrategy
{
    IEnumerable<IWorkItem> CreateWorkItems();
}

public class CreateTypeAStrategy : ICreateWorkItemsStrategy
{
    public CreateTypeAStrategy(TypeA typeA)
    {

    }
    public IEnumerable<IWorkItem> CreateWorkItems()
    {
        throw new System.NotImplementedException();
    }
}

关于如何使用 EF 代理解决的任何建议?

完整的工作示例(需要 EF 和 Autofac nuget):

public class ApplicationDbContext : DbContext
{
    public virtual DbSet<TypeA> TypeAs { get; set; }
    public virtual DbSet<RefForProxy> Refs { get; set; }
}

public class RefForProxy
{
    public int Id { get; set; }
}

public class TypeA
{
    public int Id { get; set; }
    public virtual RefForProxy Ref { get; set; }
}

public interface ICreateWorkItemsStrategy
{
    IEnumerable<object> CreateWorkItems();
}

public class CreateTypeAStrategy : ICreateWorkItemsStrategy
{
    public CreateTypeAStrategy(TypeA typeA)
    {

    }
    public IEnumerable<object> CreateWorkItems()
    {
        throw new NotImplementedException();
    }
}

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        var builder = new ContainerBuilder();
        builder.RegisterType<CreateTypeAStrategy>().Keyed<ICreateWorkItemsStrategy>(typeof(TypeA));
        var container = builder.Build();

        int a_id;
        using (var ctx = new ApplicationDbContext())
        {

            var a = new TypeA { Ref = new RefForProxy() };
            ctx.TypeAs.Add(a);
            ctx.SaveChanges();
            a_id = a.Id;
        }

        using (var ctx = new ApplicationDbContext())
        {
            var aProxy = ctx.TypeAs.SingleOrDefault(x => x.Id == a_id);

            var strategy = container.ResolveKeyed<ICreateWorkItemsStrategy>(aProxy.GetType(), new TypedParameter(aProxy.GetType(), aProxy));
        }
    }
}

【问题讨论】:

  • 我不确定如何在没有后端数据库的情况下为测试提供动态代理。
  • 您至少需要为接口和 CreateTypeAStrategy 类提供代码,并引用复制您的问题的 EF 上下文。这样人们就可以看到您尝试构建上下文的位置和方式

标签: c# entity-framework autofac dynamic-proxy


【解决方案1】:

ObjectContext.GetObjectType 是您需要的方法。

返回与指定类型的代理对象关联的 POCO 实体的实体类型。

如果指定的类型不是代理而是 POCO 类型,它也返回 POCO 类型。

Type t = ObjectContext.GetObjectType(aProxy.GetType()); 
var strategy = container.ResolveKeyed<ICreateWorkItemsStrategy>(t, new TypedParameter(t, aProxy));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-25
    • 2012-02-17
    • 1970-01-01
    • 1970-01-01
    • 2019-06-21
    • 1970-01-01
    • 2020-04-11
    • 1970-01-01
    相关资源
    最近更新 更多