我迷失了寻找这个问题的解决方案:
我有界面:
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 注册,但它以同样的方式失败。
请帮忙。我迷路了。 :(
提前完成。
答案 0 :(得分:0)
现在已经有一段时间了,因为我使用了unity,我更喜欢在代码中完全配置配置,但是:
控制器中请求的类型为[Dependency("TestService")]
,其配置为SpecificTestServiceImpl
,而SpecificTestServiceImpl
尚未配置。我本以为Unity会告诉你{{1}}没有配置,但也许它确实使用了映射类型,这是具体的
我只需要补充一点,公共成员,接口,注入的具体类型的混合是相当差的封装逻辑,并消除了适当设计的很多价值。测试控制器最好应该请求一个接口ISomeTypeTestService(或类似的),然后可以映射到BaseTestServiceImpl,或者它可以是一个可以被请求的命名ITestService,因为它现在是