2017-01-25 6 views
0

私のインタフェースsimilar to this postを実装するすべてのクラスにデータベースコンテキストを注入しようとしています。インタフェースを使用してデータベースコンテキストをクラスに挿入する

私は各サービスクラスは、現時点では私の具象クラスがどのように見えるので、この方法

interface IRecipeTypeIndexService 
{ 
    IEnumerable<RecipeType> GetAll(); 
} 

とのインタフェースすべてのサービスクラスは、抽象Serviceクラスを継承します

public abstract class Service 
{ 
    public Service(Context context) 
    { 
     Context = context; 
    } 

    public Context Context { get; } 
} 

を持つことになります持っているもの

public class RecipeTypesIndexService : Service, IRecipeTypeIndexService 
{ 
    public RecipeTypesIndexService(Context context) : base(context) 
    { 
    } 

    public IEnumerable<RecipeType> GetAll() 
    { 
     return Context.RecipeTypes.AsEnumerable(); 
    } 
} 

そして、私のninjectバインディングは次のようになります私は何をしたいのは、私のインターフェイスIRecipeTypeIndexServiceと私が作成した他のサービス・インターフェースは、Ninjectは抽象Serviceクラスに結合する他のインターフェイスIServiceIWhateverService必見を実装するので、すべての具象クラスを継承するようにそれを持っている

Kernel.Bind<DbContext>().ToSelf().InRequestScope(); 
Kernel.Bind<Service>().ToSelf().InRequestScope(); 

データベース・コンテキストを基本クラスに注入するコンストラクタを持っているので、具体的なクラスは次のようになります。

public class RecipeTypesIndexService : IRecipeTypeIndexService 
{ 
    public RecipeTypesIndexService(Context context) : base(context) 
    { 
    } 

    public IEnumerable<RecipeType> GetAll() 
    { 
     return Context.RecipeTypes.AsEnumerable(); 
    } 
} 

これは可能ですか?私はこれまでNinjectを使用したことが初めてで、依存性注入を初めて使用しています。

+0

私はあなたの基本クラスのContextプロパティにプライベートなセッターを追加する必要があると思う:public Context Context {get;プライベートセット; } – Kevin

+0

これはセッターを持たず、コンストラクタに設定されているため、プライベートセットです。 –

+0

Context = Contextプロパティは読み込み専用です(ゲッタを持ちます) – Kevin

答えて

0

UPDATE

私はこれが行うことが不可能であることを後知恵で実現しています。

Ninjectを設定して、コンストラクタ内のコンテキストが既に初期化されたコンテキストを持つように、私は抽象クラスを必要としません。

私のサービスクラスは、次のようになります。

public class RecipeTypesIndexService : IRecipeTypeIndexService 
{ 
    private Context context { get; } 

    public RecipeTypesIndexService(Context context) : base(context) 
    { 
     this.context = context; 
    } 

    public IEnumerable<RecipeType> GetAll() 
    { 
     return context.RecipeTypes.AsEnumerable(); 
    } 
} 

私はすべての抽象基本クラスを必要としません。

関連する問題