Unity和UnityContainer

时间:2017-01-29 18:42:36

标签: c# wcf unity-container

我有很多项目:

  • Service.DataAccess
  • Service.DataAccess.Interfaces
  • Service.Main
  • Service.Factory

Service.DataAccess引用Service.DataAccess.Interfaces

Service.Main引用Service.DataAccess.InterfacesService.Factory

Service.Main我有:

var instance = Service.Factory.ObjectFactory.Resolve<Service.DataAccess.Interfaces.IDataAccessLayer>();

Service.Factory

public void InitContainer(IUnityContainer container)
{
    var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");

    section.Configure(container); //Exception here!
}

在我的配置文件中:

<?xml version="1.0" encoding="utf-8" ?>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <container>
        <register type="Service.DataAccess.Interfaces.IDataAccessLayer, Service.DataAccess.Interfaces"
                  mapTo="Service.DataAccess.DataAccessLayer, Service.DataAccess" />
    </container>
</unity>

但我在运行时InitContainer方法中有一个例外:

The type name or alias Service.DataAccess.Interfaces.IDataAccessLayer could not be resolved. Please check your configuration file and verify this type name.

我不明白

感谢&#39;!小号

1 个答案:

答案 0 :(得分:1)

您的容器需要能够访问您的实现的构造函数。因此,它需要访问类Service.DataAccess.DataAccessLayer的公共构造函数,这意味着您的Service.Factory需要引用Service.DataAccess。但也Service.DataAccess.Interfaces,因为否则它将找不到界面。

您也可以将其分成几个步骤,让每个图书馆负责自己的注册。

Main如果Service.DataAccess通过Service.Factory创建它,则无需引用var container = new UnityContainer(); container.Register<IFactory, SomeFactory>(); // Factory is a class in Service.Factory. // Let your factory project take care of it's registrations as well. Service.Factory.Startup.InitContainer(container); var factory = container.Resolve<IFactory>(); Service.DataAccess.Interfaces.IDataInterface foo = factory.Create(); 。让我们举一个非常简单的例子。

主要

// Class for initiating registrations.
public static class Startup
{
    public static InitContainer(IUnityContainer container)
    {
        var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
        section.Configure(container);
    }
}

// Some example class...
public class SomeFactory : IFactory
{
    private readonly IUnityContainer _container;

    public SomeFactory(IUnityContainer container)
    {
        _container = container;
    }

    public IDataInterface Create()
    {
        // return the implementation.
        return _container.Resolve<IDataInterface>();
    }
}

Service.Factory

SomeFactory

请注意,Service.Main使用ServiceLocator anti-pattern。但它主要是一个概念验证,以展示 的工作方式。这是让Service.Factory仅引用接口而不是具体类的方法。但是,echo $python = exec("python python/interactive.py");//this file not working echo $python = passthru("python python/python.py ");// this is working with hello world. $output = shell_exec($command); echo $output; 需要引用两者。