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

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

这是我的代码:

Program.cs中

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

MainThread.cs

 namespace xxxx.Presentation.Console { public class MainThread { public IUnitOfWork UnitOfWork { get; set; } public IMapper Mapper { get; set; } public MainThread() { Mapper.RegisterMappings(); } } } 

App.config中

    

App.config设置为“始终复制”

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

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

提前致谢!

Br,Inx

Unity 仅为通过Resolve或解析子依赖项获取的组件提供依赖关系。 必须手动从容器中获取“根”组件。

使用new Program 不会自动提供依赖项,因为它会绕过Unity容器。

 static class ProgramEntry { static void Main(string[] args) { var unity = CreateUnityContainerAndRegisterComponents(); // Explicitly Resolve the "root" component or components var program = unity.Resolve(); 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(); } } 

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

  • 我建议不要使用属性,尽管如果按照上面的Resolve模式它们将会起作用。 必须手动解析“根”对象。

    属性的问题是这些依赖 Unity – 对于“反转”来说太多了!

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

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

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