我迷失了寻找解决这个问题的方法:
我有界面:
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注册,但以同样的方式失败。
请帮忙。我迷路了。:(
提前谢谢。