2017-01-25 6 views
0

내 인터페이스 similar to this post을 구현하는 모든 클래스에 데이터베이스 컨텍스트를 주입하려고합니다.인터페이스를 사용하여 데이터베이스 컨텍스트를 클래스에 삽입

나는

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

    public Context Context { get; } 
} 

는 각 서비스 클래스는 추상 Service 클래스를 상속합니다

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

모든 서비스 클래스, 그래서 순간에 내 콘크리트 클래스처럼 보이는 방법으로 인터페이스를해야합니다 무엇을 가지고

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

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

그리고 제 ninject 바인딩은 다음과 같습니다. 내가하고 싶은 무엇

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

내 인터페이스 IRecipeTypeIndexService 및 기타 서비스 인터페이스 내가 Ninject에 또 다른 인터페이스 IService이 추상 Service 클래스에 결합 상속 만들 수 있도록, IWhateverService해야을 구현하여 모든 구체적인 클래스를 가지고있다 기본 클래스에 데이터베이스 컨텍스트를 삽입하는 생성자가 있으므로 내 구체적인 클래스는 다음과 같습니다.

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

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

이 작업이 가능합니까? 이것은 처음으로 Ninject를 사용한 적이 처음이며 의존성 주입을 처음 사용했습니다.

+0

기본 클래스의 Context 속성에 전용 setter를 추가해야한다고 생각합니다. public Context Context {get; 개인 집합; } – Kevin

+0

어쨌든 setter가없고 생성자에 설정되어 있으므로 private 세트입니다 –

+0

Context = Context 속성은 읽기 전용이므로 컨텍스트가 작동하지 않습니다 (getter 만 있음) – 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(); 
    } 
} 

난 전혀 추상 기본 클래스가 필요하지 않습니다.