[英]Unity via configuration - property dependency injection in generic base class
我迷失了寻找解决此问题的方法:
我有界面:
public interface ITestService
{
...
}
然后,我有一个实现该接口的基类,并具有其他服务作为属性:
public class BaseTestServiceImpl<T> : ITestService, IDisposable where T : class
{
protected T GenericProperty;
public IOtherService OtherService;
public void ExampleMethodFromBase()
{
OtherService.DoSomething();
}
public void Dispose()
{
....
}
}
最后,我有几个继承该基类的类。 其中之一的示例:
public class SpecificTestServiceImpl : BaseTestServiceImpl<SomeType>
{
public void ExampleMethodFromSpecific()
{
OtherService.DoSomethingElse();
}
}
从SpecificTestServiceImpl调用方法的控制器如下所示:
public class TestController : Controller
{
[Dependency("TestService")]
public BaseTestServiceImpl<SomeType> TestService { get; set; }
public JsonResult TestAction()
{
TestService.ExampleMethodFromSpecific();
}
}
Unity配置如下所示:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
</configSections>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<container>
<alias alias="transient" type="Microsoft.Practices.Unity.TransientLifetimeManager, Microsoft.Practices.Unity" />
<alias alias="MyType" type="SomeType" />
<register name="otherService" type="IOtherService" mapTo="OtherServiceImpl">
<lifetime type="singleton" />
</register>
<register type="ITestService" mapTo="BaseTestServiceImpl`1[]">
<lifetime type="transient" />
<property name="OtherService" dependencyName="otherService" />
</register>
<register name="TestService" type="BaseTestServiceImpl`1[MyType]" mapTo="SpecificTestServiceImpl">
<lifetime type="singleton" />
</register>
</container>
</unity>
</configuration>
一切都可以很好地解决,直到调用TestController的 TestAction为止。 然后在此行中得到NullPointerException:
OtherService.DoSomethingElse();
在SpecificTestServiceImpl中的ExampleMethodFromSpecific方法中。
看起来Unity跳过了子类中的父属性注入。
能做到吗? 我尝试将其他生命周期管理器设置为BaseTestServiceImpl注册,但是以相同的方式失败。
请帮忙。 我迷路了。 :(
提前感谢。
自从我使用unity以来已经有一段时间了,我更喜欢完全在代码中使用配置,但是:控制器中请求的类型是[Dependency("TestService")]
,它被配置为SpecificTestServiceImpl
,而后者又没有已配置。 我以为Unity会告诉您没有配置SpecificTestServiceImpl
,但是也许它确实使用了映射类型,这是具体的
我只需要补充一点,公共成员,接口,注入的具体类型的这种混合是相当差的封装逻辑,并且消除了适当设计可能带来的很多价值。 测试控制器最好应请求一个ISomeTypeTestService接口(或类似接口),该接口又可以映射到BaseTestServiceImpl,或者可以是一个命名的ITestService,可以像现在这样被请求
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.