【发布时间】:2012-07-30 11:21:28
【问题描述】:
我迷失了寻找解决这个问题的方法:
我有接口:
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 注册,但以同样的方式失败。
请帮忙。我迷路了。 :(
提前感谢。
【问题讨论】:
-
为什么要在 XML 中拥有完整的配置?您应该只在 XML 中配置在部署期间实际上可以更改的部分 DI 配置。其余的,使用基于代码的配置,因为基于 XML 的配置表达能力较差、更脆弱、容易出错且难以维护。
标签: c# inheritance configuration dependency-injection unity-container