统一同界面,多工厂

本文关键字:工厂 界面 | 更新日期: 2023-09-27 18:31:17

所以问题是,当我声明:

[Dependency]
public AuthenticationService _authenticationServices { get; set; }

_authenticationServices将一直保持null. 它未被引用,这将引发 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(...);
     }
}

我想保留这种结构,以避免代码重复。

统一同界面,多工厂

你想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;}
     }
}

我最终通过为每个通用存储库创建特定的容器来解决这个问题。

public interface IZNodeContextFactory : ICrudFactory
{
}
public interface IMincronContextFactory : ICrudFactory
{
}

通过以这种方式做到这一点,我能够简单地做到:

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

这允许自动依赖项解析程序工作和实现,因为它们现在具有唯一的名称。