【发布时间】: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