如何使用IoC DI与这种存储库模式? [英] How should I use IoC DI with this repository pattern?
问题描述
我正在使用在这个SO问题的答案中找到的存储库模式:
即,每个存储库都继承自包含通用方法(如add,delete等)的抽象基类,并且还为该存储库/实体唯一的任何方法实现了特定的存储库接口。 p>
ie。
public class CompanyRepository:Repository< Company>,ICompanyRepository {
...
}
在我的业务层我正在使用结构图获取存储库的一个实例,但我不确定如何使用它。
//结构图初始化
ObjectFactory.Initialize(
x =>
{
x.For< ICompanyRepository>()使用<。&CompanyRepository GT;();
});
解决一个实例:
return ObjectFactory.GetInstance< ICompanyRepository>();
然而,我得到的实例是一个接口,而不是整个存储库实现。我无法访问基类( Repository< Company>
)上的方法。通常的方法是这样做?
这里的关键是想到 Repository& ;
仅作为实现细节。你不会直接访问任何方法;相反,您将在界面上公开所有方法,包括 Insert
和 Delete
,
public interface ICustomerRepository
{
// ...客户特定的查询...
void插入(客户客户);
void删除(客户客户);
}
在 CustomerRepository
,您只需将插入
和删除
调用到<$ c的受保护方法$ c> Repository<> 如原始问题所述。
您在问题中所述的StructureMap注册正是我期望的。然后, Repository<>
的目的是帮助实现特定于实体的接口。请记住,接口将始终包含存储库的完整公共API,并且应该指向正确的方向。
I am using the repository pattern found in the answer to this SO question:
Advantage of creating a generic repository vs. specific repository for each object?
Namely, each repository inherits from an abstract base class that contains generic methods like add, delete, etc. and also implements a specific repository interface for any methods that are unique to that repository/entity.
ie.
public class CompanyRepository : Repository<Company>, ICompanyRepository {
...
}
In my business layer I am using Structure Map to get an instance of the repository, but I am unsure how to use it.
// Structure Map initialisation
ObjectFactory.Initialize(
x =>
{
x.For<ICompanyRepository>().Use<CompanyRepository>();
});
resolving an instance:
return ObjectFactory.GetInstance<ICompanyRepository>();
However the instance I get is an interface and not the whole repository implementation. I don't have access to the methods on the base class (Repository<Company>
). What is the usual way to do this?
The key here is to think of Repository<>
solely as an implementation detail. You won't be accessing any methods on it directly; instead, you will expose all methods, including Insert
and Delete
, on the interface:
public interface ICustomerRepository
{
// ...Customer-specific queries...
void Insert(Customer customer);
void Delete(Customer customer);
}
When you implement the interface in CustomerRepository
, you simply have to pass the Insert
and Delete
calls through to the protected methods of Repository<>
as discussed in the original question.
The StructureMap registration you state in the question is exactly what I would expect. The purpose of Repository<>
then is to aid in the implementation of entity-specific interfaces. Keep in mind that the interfaces will always contain the repository's full public API and that should point you in the right direction.
这篇关于如何使用IoC DI与这种存储库模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!