2016-09-22 5 views
0

は、私は2つの複雑なクラスを持っています。このフォーマットBaseRepository.Get(へUserServiceの呼び出しのインスタンスを使用してオーバーライド財産紛争

public class UserRepository : BaseRepository<User> 
{ 
    public User Get(object id) 
    { 
     // Do specific user get including Role DP 
     return context.Users.Include("Role").Find(id); 
    } 
} 

public class UserService : BaseService<User> 
{ 
    public UserRepository repo = new UserRepository(); 
} 

)の代わりUserRepository.Getの()。 、「ゲット

public class UserService : BaseService<User> 
{ 
    public UserRepository repo = new UserRepository(); 

    public User Get(object id) 
    { 
     // This call to UserRepository.Get() 
     return repo.Get(id); 
    } 
} 

本当の問題は、私が29、「リポジトリ」を持っているということですので、私は追加「(int)を取得する」必要があります。

私がやりたいための唯一の方法は、このようなコードを複製しています(エンティティ)」、「保存(IEnumerable)」、「削除(エンティティ)」、「削除(IEnumerable)」などのコードを作成することができます。

BaseServiceのメソッドがrepoサブクラスを呼び出すように、BaseServiceのプロパティ "repo"を置き換える方法はありますか?

答えて

3

BaseService<T>.repoフィールド(実際にはプロパティではなく、パブリックフィールドを使用することをお勧めしますが、それは別の問題です)のためのものですタイプ。十分に簡単です。BaseService<T>で作成しないでください。 UserServiceが他の値を提供されていない場合、あなただけのレポを取るためにService<T>、非抽象と公共コンストラクタとが必要になる場合があり、実際には

// Type parameter renamed to follow normal .NET naming conventions 
public abstract class BaseService<T> where T : class 
{ 
    private readonly BaseRepository<T> repo; 

    protected BaseService(BaseRepository<T> repo) 
    { 
     this.repo = repo; 
    } 

    public T Get(object id) 
    { 
     // Do generic get entities 
     return repo.Get(id); 
    } 
} 

public class UserService : BaseService<User> 
{ 
    public UserService() : base(new UserRepository()) 
    { 
    } 
} 

:代わりに、コンストラクタチェーンをそれを渡します。それでは、あなたはただ使っています:

var userService = new Service<User>(new UserRepository()); 

たとえば、

+0

これの最も重要な部分は、DIが使いやすいことです。 –

+0

私は本当にそれを行いますが、BaseRepositoryが "Get"を定義していればUseRepositoryのGetメソッドをオーバーライドできません。 BaseRepository.Get()はcontext.Setを返します。().Find(id)のみオーバーライドされたレポにこのメソッドがない場合。 – Pythonizo

+0

すべてありがとう。あなたの助けを借りてこれを解決し、BaseService.Get()に "virtual"を追加し、UserService.Get()に "オーバーライド"してください。 – Pythonizo