所以,問題是,當我宣佈:統一使用相同的接口,多個工廠
[Dependency]
public AuthenticationService _authenticationServices { get; set; }
的_authenticationServices
將不斷保持null
。它沒有被引用,它會拋出一個空引用異常。我假設這個問題源於我的Unity配置文件:
container.RegisterType<ICrudFactory, ZNodeDataContextFactory>();
container.RegisterType<ICrudFactory, MincronDataContextFactory>();
因爲它們都使用相同的接口,而是單獨的具體實現。實現如下:
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(...);
}
}
我想保持這種結構,以避免代碼重複。
'AuthenticationService'與工廠有什麼關係? –
@YacoubMassad編輯爲包含驗證服務。 – Greg
你想注入'AuthenticationService'的哪個'ICrudFactory'實現? –