c#DI Unity Container如何解析依赖对象

时间:2014-02-22 16:50:22

标签: c# dependency-injection unity-container

我们有以下IProduct& amp; ILogger课程。管理器类被用作通信通道。我们使用下面给出的unity解析了管理器类,但它给出了以下错误 -

===================unity configuration==========

IUnityContainer container = new UnityContainer();
container.RegisterType<ILogger, FileLogger>("File");
container.RegisterType<ILogger, BDLogger>("DB");

container.RegisterType<IProduct, ProductA>("productA");
container.RegisterType<IProduct, ProductB>("productB");

container.RegisterType<ProducManager>(new InjectionConstructor(container.Resolve<IProduct>("productA")));

container.Resolve<ProducManager>("productA");

========================================================
  

“依赖关系的解析失败,输入= \”usingDI.IProduct \“,   name = \“productA \”。\ r \ n在:while时发生异常   解析。\ r \ n \ nException是:InvalidOperationException - 当前   type,usingDI.ILogger,是一个接口,无法构造。是   你错过了一个类型   映射吗?\ r \ n -------------------------------------------- --- \ r \ nAtt   异常时间,容器是:\ r \ n \ r \ n解析   usingDI.ProductA,productA(从usingDI.IProduct,productA映射)\ r \ n   解析构造函数的参数\“logger \”   usingDI.ProductA(usingDI.ILogger logger)\ r \ n解析   usingDI.ILogger,(无)\ r \ n “}”

请建议我解决经理类依赖的最佳方法。

public interface IProduct
{
    void dosomething();
}

public class ProducManager
{
    IProduct _product;
    public ProducManager(IProduct product)
    {
        _product = product;
    }

    public void DoSomething()
    {
        _product.dosomething();
    }
}

public class ProductA : IProduct
{
    ILogger _logger;
    public ProductA(ILogger logger)
    {
        _logger = logger;
    }

    public void dosomething()
    {

        try
        {
            //code
            //
        }
        catch (Exception ex)
        {
            _logger.WriteLog(ex.Message);
        }
    }
}

public class ProductB : IProduct
{
    ILogger _logger;
    public ProductB(ILogger logger)
    {
        _logger = logger;
    }

    public void dosomething()
    {

        try
        {
            //code
            //
        }
        catch (Exception ex)
        {
            _logger.WriteLog(ex.Message);
        }
    }
}
public class LogManager
{
    ILogger _logger;
    public LogManager(ILogger logger)
    {
        _logger = logger;
    }

    public void WriteLog(string exception)
    {
        _logger.WriteLog(exception);
    }
}

public interface ILogger
{
    void WriteLog(string exception);
}

public class FileLogger : ILogger
{

    public void WriteLog(string exception)
    {

    }
}

public class BDLogger : ILogger
{

    public void WriteLog(string exception)
    {

    }
}

1 个答案:

答案 0 :(得分:1)

您需要为接口ILogger注册类型映射。否则,Unity现在不应该使用ILogger的哪个实现(请参阅您的例外)。

这是一个注册接口ILogger的示例,其映射到FileLogger

_container.RegisterType<ILogger, FileLogger>();

IProduct product = _container.Resolve<ProductA>(); //ILogger is injected to Product