我正在尝试使用统一每次使用新实例在我的存储库中自动注入数据上下文..,我的想法是确保每次注入新的数据上下文
目前它未能创建存储库,我认为它无法解决 MyDataContext
在“存储库”(见下文)上创建构造函数以获取存储库上的 DataContext 之前,一切正常,但现在失败了。
我目前在我在 global.asax 中创建的统一容器中有这个设置,我还注册了 MyDataContext 类型,它是标准 DataContext
container = new UnityContainer();
Container.RegisterType<MyDataContext, MyDataContext>()
.RegisterType<IOfficeRepository, OfficeRepository>()
.RegisterType<IOfficeService, OfficeService>();
基本上我有一个像这样调用存储库的服务
public class OfficeService : IOfficeService
{
IOfficeRepository repository = null;
public OfficeService(IOfficeRepository repository)
{
this.repository = repository;
if (this.repository == null)
throw new InvalidOperationException("Repository cannot be null");
}
这是我的存储库
public class OfficeRepository : IOfficeRepository
{
private MyDataContext db;
public OfficeRepository (MyDataContext dataContext)
{
this.db = dataContext;
}
编辑
我差点忘了我这样做是为了创建服务
officeService = Bootstrapper.Container.Resolve<IOfficeService>();
编辑 - 正在生成的错误
Resolution of the dependency failed, type = "MarkSmith.IOfficeService", name = "".
Exception message is: The current build operation (build key Build
Key[MarkSmith.OfficeService, null]) failed: The parameter repository could not be
resolved when attempting to call constructor
MarkSmith.OfficeService(MarkSmith.IOfficeRepository repository). (Strategy type BuildPlanStrategy, index 3)
编辑-删除存储库上的构造函数
这与数据上下文有关,因为如果我删除存储库上采用 DataContext 的构造函数,那么一切正常,但我当然需要它接受 DataContext 才能每次都注入“新”数据上下文
public class OfficeRepository : IOfficeRepository
{
private MyDataContext db new MyDataContext(); // CHANGE
//public OfficeRepository (MyDataContext dataContext)
//{
//this.db = dataContext;
//}
编辑 - 实际错误
深入挖掘后,我发现了这个错误....
The type MyDataContext has multiple constructors of length 2.
Unable to disambiguate. (Strategy type DynamicMethodConstructorStrategy, index 0)
(Strategy type BuildPlanStrategy, index 3)
编辑 - 测试以使用 1 行代码解析 DATACONTEXT
这也失败并出现与上述相同的错误 - 多个构造函数
MyDataContext test = Bootstrapper.Container.Resolve<MyDataContext >();
编辑 - 我的数据上下文中的所有构造函数
这些是由外部实用程序创建的,但一切都应该很好..
[System.Diagnostics.DebuggerNonUserCode]
public MyDataContext()
: base(ConnectionString, mappingCache)
{
OnCreated();
}
[System.Diagnostics.DebuggerNonUserCode]
public MyDataContext(string connection)
: base(connection, mappingCache)
{
OnCreated();
}
[System.Diagnostics.DebuggerNonUserCode]
public MyDataContext(System.Data.IDbConnection connection)
: base(connection, mappingCache)
{
OnCreated();
}
[System.Diagnostics.DebuggerNonUserCode]
public MyDataContext(string connection, System.Data.Linq.Mapping.MappingSource mappingSource)
: base(connection, mappingSource)
{
OnCreated();
}
[System.Diagnostics.DebuggerNonUserCode]
public MyDataContext(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource)
: base(connection, mappingSource)
{
OnCreated();
}
编辑 - 演示在没有 Unity 的代码中创建 DataContext 100% 没有问题
MyDataContext tes2t = new MyDataContext ();