0

我已經創建了一個泛型類型簡單的注射器:註冊開放式泛型類型與構造函數的參數

public interface IContext<T> {}

而且,我有一個類型實現的是(與參數的構造函數)

public class Context<T> : IContext<T> { public Context(string url, string key) { } ... }

我想註冊簡單的注射器。通過下面的代碼,我不知道如何通過值構造

container.Register(typeof(IContext<>), typeof(Context<>))

This一個顯示了一種方法,如果我在構造函數的參數傳遞的類型。但是,對我而言,它只是原始類型。看起來像是通過壓倒一切的施工解決方案行爲,我可能做到這一點。但是,真的不知道我該如何利用它。有人能指導我找到一個合適的方式來註冊嗎?

回答

1

在將原始依賴關係轉換爲開放通用註冊時,典型的解決方案是將一組配置值提取到DTO中,並將該DTO注入到類型的構造函數中;這可以讓你新的配置對象爲單登記到container:

我已經創建了一個泛型類型

公共接口IContext {}

而且,我已經實現了一個類型(有一個構造函數與參數)

public class ContextConfiguration 
{ 
    public readonly string Url; 
    public readonly string Key; 
    public ContextConfiguration(string url, string key) { ... } 
} 

public class Context<T> : IContext<T> 
{ 
    public Context(ContextConfiguration config) 
    { 
    } 
    ... 
} 

// Configuration 
container.RegisterSingleton(new ContextConfiguration(...)); 
container.Register(typeof(IContext<>), typeof(Context<>)); 

如果你不能改變該類型的構造函數中,創建一個子類,類型您將Composition Root內的。該子類型再次使用該配置DTO:

// Part of the Composition Root 
private class ContextConfiguration 
{ 
    public readonly string Url; 
    public readonly string Key; 
    public ContextConfiguration(string url, string key) { ... } 
} 

private class CompositionRootContext<T> : Context<T> 
{ 
    public Context(ContextConfiguration config) : base(config.Url, config.Key) 
    { 
    } 
    ... 
} 

// Configuration 
container.RegisterSingleton(new ContextConfiguration(...)); 
container.Register(typeof(IContext<>), typeof(CompositionRootContext<>)); 

如果Context<T>是密封的,你可以覆蓋parameter injection behavior,但在一般情況下,在這種情況下,你是在處理由外部庫定義的類型。對於外部類型,通常最好將它們隱藏在應用程序定製的抽象之後(根據DIP)。不要讓應用程序代碼依賴於IContext<T>,而是讓應用程序依賴於應用程序定義的接口。作爲組合根的一部分,您可以實現一個Adapter,將特定於應用程序的界面調整爲Context<T>。該適配器的構造函數將能夠使用該配置DTO。

+0

感謝您的見解史蒂文。我想我可以按照你的建議創建一個DTO。但是,爲什麼我會將其註冊爲單身人士?我不能在運行時傳遞參數嗎? (我的要求也是在運行時通過它們) –

+0

@AthiS:啊,那是你的問題中缺少的一些重要信息。值是_runtime _data_。請閱讀[本文](https://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=99)。它描述瞭如何處理運行時數據。 – Steven

+0

有趣的閱讀史蒂文。通過輸入,我改變了設計,以便運行時數據不會通過構造函數傳遞 –

相關問題