Csharp/C#教程:将Unity DI与控制台应用程序配合使用分享


将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(); } } 

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

上述就是C#学习教程:将Unity DI与控制台应用程序配合使用分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1000284.html

(0)
上一篇 2021年12月27日
下一篇 2021年12月27日

精彩推荐