Unity InjectionFactory 没有 运行
Unity InjectionFactory Doesn't Run
总结:似乎 InjectionFactory 没有被 运行 用于类型映射。我想知道为什么以及如何解决这个问题。
起初,我尝试注册接口
Container.RegisterType<ILogger>(new InjectionFactory((c, t, n) => {
return LogManager.GetLogger(n);
}));
并使用服务定位器解决
ServiceLocator.GetInstance<ILogger>("Operation Manager");
这导致
The current type, NLog.ILogger, is an interface and cannot be constructed. Are you missing a type mapping?
经过一些修改,我决定尝试一种不同的方法并使用具体类型注册服务
Container.RegisterType<Logger>(new InjectionFactory((c, t, n) => {
return LogManager.GetLogger(n);
}));
并将解析方式改为
public OperationService([Dependency("Operation Service")]Logger logger)
这会导致以下错误:
The type Logger does not have an accessible constructor.
我能想到的造成这种行为的唯一原因是,如果我通过 InjectionFactory 传递的函数实际上没有被调用来解析对象。
这是因为您注册的类型没有名称,而您正试图通过名称解析它。 Unity 寻找 (ILogger, "Operation Manager")
的注册,但找不到任何注册。您没有姓名的注册永远不会被视为合格候选人,因此不会调用 InjectionFactory
。
据我所知,没有内置方法可以实现您想要做的事情。自定义扩展可能是可行的,但到目前为止我的尝试都没有成功。
总结:似乎 InjectionFactory 没有被 运行 用于类型映射。我想知道为什么以及如何解决这个问题。
起初,我尝试注册接口
Container.RegisterType<ILogger>(new InjectionFactory((c, t, n) => {
return LogManager.GetLogger(n);
}));
并使用服务定位器解决
ServiceLocator.GetInstance<ILogger>("Operation Manager");
这导致
The current type, NLog.ILogger, is an interface and cannot be constructed. Are you missing a type mapping?
经过一些修改,我决定尝试一种不同的方法并使用具体类型注册服务
Container.RegisterType<Logger>(new InjectionFactory((c, t, n) => {
return LogManager.GetLogger(n);
}));
并将解析方式改为
public OperationService([Dependency("Operation Service")]Logger logger)
这会导致以下错误:
The type Logger does not have an accessible constructor.
我能想到的造成这种行为的唯一原因是,如果我通过 InjectionFactory 传递的函数实际上没有被调用来解析对象。
这是因为您注册的类型没有名称,而您正试图通过名称解析它。 Unity 寻找 (ILogger, "Operation Manager")
的注册,但找不到任何注册。您没有姓名的注册永远不会被视为合格候选人,因此不会调用 InjectionFactory
。
据我所知,没有内置方法可以实现您想要做的事情。自定义扩展可能是可行的,但到目前为止我的尝试都没有成功。