簡體   English   中英

通過配置實現統一-通用基類中的屬性依賴注入

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM