1

所以,問題是,當我宣佈:統一使用相同的接口,多個工廠

[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(...); 
    } 
} 

我想保持這種結構,以避免代碼重複。

+0

'AuthenticationService'與工廠有什麼關係? –

+0

@YacoubMassad編輯爲包含驗證服務。 – Greg

+0

你想注入'AuthenticationService'的哪個'ICrudFactory'實現? –

回答

0

我最終解決這個問題,通過爲每個通用庫創建特定的容器。

public interface IZNodeContextFactory : ICrudFactory 
{ 

} 

public interface IMincronContextFactory : ICrudFactory 
{ 

} 

通過這種方式這樣做,我可以簡單地做:

container.RegisterType<IZNodeContextFactory, ZNodeContextFactory>(); 
container.RegisterType<IMincronContextFactory, MincronContextFactory>(); 

這使得自動依賴解析器的工作,並執行,因爲他們現在有了唯一的名稱。

1

是否要將ZNodeDataContextFactory注入AuthenticationService?注入的一點是,該服務現在不應該與實現有關。但是如果你真的想要一個特定的實現,你可以創建一個命名實例。

public class AuthenticationService 
{ 
    private readonly ICrudFactory _factory; 
    public AuthenticationService([Dependency("ZNodeData")] ICrudFactory factory) 
    { 
     _factory = factory; 
    } 
} 

而在你的配置:

container.RegisterType<ICrudFactory, ZNodeDataContextFactory>("ZNodeData"); 
container.RegisterType<ICrudFactory, MincronDataContextFactory>("MincronData"); 

或者:

public class AuthenticationService 
    { 
     private readonly IEnumerable<ICrudFactory> _factories; 
     public AuthenticationService(ICrudFactory[] factories) 
     { 
      // Now you got both... 
      _factories = factories; 
      var zNodeFactory = _factories.FirstOrDefault(x => x.Factory == ZNode); 
     } 
    } 


    public interface ICrudFactory 
    { 
     ICrud Create(); 
     // Something to identify the type of data. Maybe an enum? 
     FactoryType Factory {get;} 
    } 

public ZNodeDataContextFactory : ICrudFactory 
{ 
    ICrud ICrudFactory.Create() 
    { 
      return ZNodeDataContext(); 
    } 

    FactoryType ICrudFactory.Factory 
    { 
     {get {return FactoryType.ZNode;} 
    } 
}