Unity InjectionConstructor in Web.config

本文关键字:config Web in InjectionConstructor Unity | 更新日期: 2023-09-27 18:14:15

在Unity中,什么是Web ?配置相当于以下c#代码:

container
    .RegisterType<IRepositoryProvider, RepositoryProvider>(
        new PerRequestLifetimeManager(),
        new InjectionConstructor(new object[] { new RepositoryFactories() })
    );

我尝试了以下操作,但没有成功:

<register type="Repository.Pattern.Ef6.Factories.IRepositoryProvider, Repository.Pattern.Ef6" mapTo="Repository.Pattern.Ef6.Factories.RepositoryProvider, Repository.Pattern.Ef6">
    <lifetime type="Microsoft.Practices.Unity.PerRequestLifetimeManager, Microsoft.Practices.Unity.Mvc" />
    <constructor>
        <param name="repositoryFactories" value="new object[]{new RepositoryFactories()}"/>
    </constructor>
</register>

困难的部分是如何处理"new object[]{new RepositoryFactories()}"

Unity InjectionConstructor in Web.config

我认为你的配置不太正确。您需要依赖项attr。请参阅下面的示例,它可以工作。

统一配置:

<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<namespace name="ConsoleApplication8" />
<assembly name="ConsoleApplication8" />
<container name="MyContainer">
  <types>
    <type type="ConsoleApplication8.IRepositoryFactories, ConsoleApplication8"
           mapTo="ConsoleApplication8.RepositoryFactories, 
           ConsoleApplication8" />
    <type type="ConsoleApplication8.IRepositoryProvider, ConsoleApplication8"
           mapTo="ConsoleApplication8.RepositoryProvider, ConsoleApplication8"
           name="RepositoryProvider" >
      <lifetime type="singleton" />
      <constructor>
        <param name="factories">
          <dependency />
        </param>
      </constructor>
    </type>
  </types>
</container>

可能不需要完全限定名作为程序集名称,并且名称空间已注册。

类型:

public interface IRepositoryProvider
{}
public class RepositoryProvider : IRepositoryProvider
{
    private IRepositoryFactories _factories;
    private string _name;
    public RepositoryProvider(IRepositoryFactories factories) {
        _factories = factories;
    }
    public RepositoryProvider(string name) {
        _name = name;
    }
}
public interface IRepositoryFactories { }
public class RepositoryFactories : IRepositoryFactories{}
class Program
{
    static void Main(string[] args)
    {
        IUnityContainer container = new UnityContainer();
        container.LoadConfiguration("MyContainer");
        var instance = container.
                           Resolve<IRepositoryProvider>("RepositoryProvider");
    }
}