8

プロジェクトで IoC コンテナーとして Ninject を使用しています。私は次のクラスを持っています:

public class SomeRepository:ISomeRepository
{
    public SomeRepository(string someDatabaseConnectionString)
    {
        // some code here..
    }
}

私のアプリケーション設定ファイルには、「someDatabase」という名前の接続文字列があります。デフォルトでは、この接続文字列をコンストラクターに挿入するには、次の構成を追加する必要があります。

kernel.Bind<ISomeRepository>()
    .To<SomeRepository>()
    .WithConstructorArgument("someDatabaseConnectionString", connString);

しかし、私はそのような文字列の従来のベースのバインディングを実装したいと考えています。名前が「ConnectionString」で終わる文字列型のすべてのコンストラクター パラメーターの値は、アプリケーションの connectionStrings 構成セクションから取得され、自動的に挿入される必要があります。appSettings セクションにも同様の規則を実装したいと考えています。このアプローチについては、Mark Seeman の記事「プリミティブの依存関係」 (「プリミティブの規約」セクション)で詳しく説明しています。例では Castle Windsor コンテナが使用されました。

Ninjectを使用してそのような規則を実装することは可能ですか?これを行う最良の方法は何ですか? 私はすでに ninject.extensions.conventions を試しましたが、そのような機能はないようです。

4

1 に答える 1

1

現在、Ninjectではそのような規則ベースのバインディングが可能ではないようです。私はここで同様の質問をしました、そして提案は接続文字列を返すためのインターフェースを作り、それをパラメータとして持つことでした。ただし、これは多くの異なる接続文字列では面倒な場合があります。

これは単なる考えですが、IConnectionStringProvider<T> リフレクションを使用してTの名前を取得し、そのようにアプリケーション設定を検索できるものがありますか?多分このように:

public class ConnectionStringProvider<T> : IConnectionStringProvider<T>
{
    public string Value
    {
        // use reflection to get name of T
        // look up connection string based on the name
        // return the connection string
    }
}
...
public class SomeRepository:ISomeRepository
{
    public SomeRepository(IConnectionStringProvider<SomeRepository> connectionStringProvider)
    {
        this.connectionString = connectionStringProvider.Value;
    }
}

また、それが機能しない場合はIConnectionStringProvider、引数として型をとる非ジェネリックを使用できます。

public class ConnectionStringProvider : IConnectionStringProvider
{
    public string GetValueFor(Type type)
    {
        // use reflection to get name of type
        // look up connection string based on the name
        // return the connection string
    }
}
...
public class SomeRepository:ISomeRepository
{
    public SomeRepository(IConnectionStringProvider connectionStringProvider)
    {
        this.connectionString = connectionStringProvider.GetValueFor(this.GetType());
    }
}

これらのいずれかが機能する場合は、任意のDIコンテナで機能するという利点があります。

于 2012-09-21T16:57:32.377 に答える