统一使用相同的接口,多个工厂 [英] Unity with the same interface, multiple factories

查看:153
本文介绍了统一使用相同的接口,多个工厂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,问题是,当我宣布:

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.

这篇关于统一使用相同的接口,多个工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆