C# 在控制台应用程序中使用Unity DI
然而,我正试图让Unity与我的控制台应用程序一起工作。。我尝试注入依赖项的所有属性仍然设置为null 这是我的代码: Program.csC# 在控制台应用程序中使用Unity DI,c#,console,unity-container,C#,Console,Unity Container,然而,我正试图让Unity与我的控制台应用程序一起工作。。我尝试注入依赖项的所有属性仍然设置为null 这是我的代码: Program.cs namespace .Presentation.Console { class Program { static void Main(string[] args) { var mainThread = new MainThread(); } } } MainT
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
<?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>
App.config设置为始终复制
在这种情况下,映射器返回为null(我假设UnitOfWork也是)
我还需要做什么吗?是否向app.config添加内容?我错过什么了吗
提前谢谢
比尔,
InxUnity仅为通过Resolve
或在解析子依赖项时获得的组件提供依赖项。必须手动从容器中获取“根”组件
使用newprogram
不会自动提供依赖项,因为它绕过了Unity容器
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();
}
}
静态类程序条目
{
静态void Main(字符串[]参数)
{
var unity=CreateUnityContainerAndRegisterComponents();
//显式解析“根”组件或多个组件
var program=unity.Resolve();
program.Run();
}
}
公共课程
{
只读Ix_x;
//这些依赖关系将自动解决
//(在这种情况下,提供给建造商)
公共程序(IMapper映射器,Ix x)
{
//使用依赖项
mapper.RegisterMappings();
//分配任何相关的财产等。
_x=x;
}
//在这里做实际工作
公开募捐{
_x、 DoStuff();
}
}
对于大多数任务,我更喜欢基于代码的注册
- 我建议不要使用属性,尽管如果遵循上面的
模式,它们“会起作用”。必须手动解析“根”对象 属性的问题是,这些属性增加了对统一的依赖性-关于“反转”就到此为止 构造函数注入(如图所示)是自动/默认的。查看是否首选属性注入Resolve
- 我可能会解析一个工厂(或
)来创建一个UoW,并在调用堆栈上下文中提供它(例如,将它传递给方法)。应用程序在一次运行期间可能有许多不同的UOW。在这种情况下,您可能还对创建作用域感兴趣Func
- 我还可能在解析时使用工厂来创建预配置的IMapper对象,而不是在解析后使用RegisterMappings
容器创建实例。解析(或者将其作为链的一部分自动解析)。。Unity对new
没有任何作用。