将Unity DI与控制台应用程序配合使用

Inx*_*x51 4 c# console unity-container

我试图让Unity与我的控制台应用程序一起工作,但是我尝试依赖注入的所有属性仍然设置为null.

这是我的代码:

Program.cs中

namespace .Presentation.Console
{
    class Program
    {
        static void Main(string[] args)
        {
            var mainThread = new MainThread();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

MainThread.cs

namespace xxxx.Presentation.Console
{
    public class MainThread
    {
        public IUnitOfWork UnitOfWork { get; set; }

        public IMapper Mapper { get; set; }

        public MainThread()
        {
            Mapper.RegisterMappings();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

App.config中

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />
  </startup>
  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <alias alias="IDataAccess" type="UnityFramework.IDataAccess, UnityFramework" />
    <namespace name="UnityFramework" />
    <assembly name="UnityFramework" />
    <container>
      <types>

        <type type="IMapper" mapTo="xxxx.Core.Parse.ParseMapper" />

      </types>
    </container>
  </unity>
</configuration>
Run Code Online (Sandbox Code Playgroud)

App.config设置为"始终复制"

在这种情况下,Mapper返回为null(我假设UnitOfWork也是如此)

我还需要做其他事吗?在app.config中添加一些东西?我错过了什么吗?

提前致谢!

Br,Inx

use*_*740 12

Unity 仅为通过Resolve解析子依赖关系或在解析子依赖关系时获取的组件提供依赖关系.必须手动从容器中获取"根"组件.

使用new Program不会因为它绕过了统一容器自动提供的依赖关系.

static class ProgramEntry
{
    static void Main(string[] args)
    {
        var unity = CreateUnityContainerAndRegisterComponents();
        // Explicitly Resolve the "root" component or components
        var program = unity.Resolve<Program>();
        program.Run();
    }
}

public class Program
{
    readonly Ix _x;

    // These dependencies will be automatically resolved
    // (and in this case supplied to the constructor)
    public Program(IMapper mapper, Ix x)
    {
        // Use dependencies
        mapper.RegisterMappings();

        // Assign any relevant properties, etc.
        _x = x;
    }

    // Do actual work here
    public void Run() {
        _x.DoStuff();
    }
}
Run Code Online (Sandbox Code Playgroud)

对于大多数任务,我更喜欢基于代码的注册.

  • 我建议不要使用属性,尽管如果遵循Resolve上面的模式,它们"会起作用" .必须手动解析"根"对象.

    属性的问题是这些 Unity 增加了依赖性- 对于"反转"来说太多了!

    构造函数注入(如图所示)是自动/默认的.如果首选属性注入,请参阅Unity中没有属性的Setter/property injection.

  • 我可能会解决一个工厂(或Func<UoW>)创建一个UoW并在适用时将其提供给调用堆栈上下文(即将其传递给方法).应用程序在单次运行期间可能有许多不同的UoW.在这种情况下,您可能也有兴趣创建范围.

  • 我也可能会使用工厂在解析时创建预先配置的IMapper对象,而不是之后使用RegisterMappings.