统一使用相同的接口,多个工厂
所以,问题是,当我宣布:
So the issue, is when I declare:
[Dependency]
public AuthenticationService _authenticationServices { get; set; }
的 _authenticationServices
将不断保持空
。它不被引用,这将抛出一个空引用异常。我假设的问题,从我的统一配置文件茎:
The _authenticationServices
will constantly remain null
. It isn't referenced, which will throw a Null Reference Exception. I'm assuming the issue stems from my Unity Configuration file:
container.RegisterType<ICrudFactory, ZNodeDataContextFactory>();
container.RegisterType<ICrudFactory, MincronDataContextFactory>();
因为它们都使用相同的接口,而是一个独立的具体实施。实现如下:
Since they both use the same interface, but a separate concrete implementation. The implementation is as follows:
public interface ICrud : IDisposable
{
// Method's to be exposed, via general repository.
}
public interface ICrudFactory
{
ICrud Create();
}
public ZNodeDataContext : DbContext, ICrud
{
// Concrete implementation.
}
public MincronDataContext : DbContext, ICrud
{
// Concrete implementation.
}
public ZNodeDataContextFactory : ICrudFactory
{
ICrud ICrudFactory.Create()
{
return ZNodeDataContext();
}
}
public MincronDataContextFactory : ICrudFactory
{
ICrud ICrudFactory.Create()
{
return MincronDataContext();
}
}
public class AuthenticationService
{
private readonly ICrudFactory _factory;
public AuthenticationService(ICrudFactory factory)
{
_factory = factory;
}
public void Sample()
{
using(var context = _factory.Create())
context.Method(...);
}
}
我想保持这种结构,避免code重复。
I'd like to keep that structure, to avoid code duplication.
我最终解决这个问题,通过为每个通用库创建特定的容器中。
I ended up solving the issue, by creating particular containers for each generic repository.
public interface IZNodeContextFactory : ICrudFactory
{
}
public interface IMincronContextFactory : ICrudFactory
{
}
通过这种方式做,我可以简单地做:
By doing it in this manner, I was able to simply do:
container.RegisterType<IZNodeContextFactory, ZNodeContextFactory>();
container.RegisterType<IMincronContextFactory, MincronContextFactory>();
这允许自动依赖解析器的工作,贯彻因为他们现在唯一的名称。
This allowed the automatic dependency resolver to work, and implement since they now had unique names.