[英]Static Method on Domain/Model Object with Repository
I have separate repository classes for each entity. 我为每个实体都有单独的存储库类。 Now I would like to implement few static methods on domain object which uses repository instance, but the drawback of this approach is that, I have to hold repository instance on the static variable(which not works well on web application) or I have to create new instance on each static method.
现在,我想在使用存储库实例的域对象上实现一些静态方法,但是这种方法的缺点是,我必须将存储库实例保存在静态变量上(不适用于Web应用程序),或者必须创建每个静态方法上的新实例。 Is there any better approach for this(ie to implement static method on domain class with repository instance)?
有没有更好的方法(即在具有存储库实例的域类上实现静态方法)? please share your ideas.
请分享您的想法。
Base repository: 基础资料库:
public abstract class AbstractRepository<TEntity> : IabstractRepository<TEntity>
where TEntity : EntityObject
{
protected CivilRegistryEntities civilContext;
public AbstractRepository()
{
civilContext = CivilRegistryEntities.Instance; // Per HTTP request singletone.
}
// Other method implementation goes here.
}
Per entity repository: 每个实体存储库:
public class BirthReportRepository : AbstractRepository<BirthReport>
{
}
Domain/Entity/Model object: 域/实体/模型对象:
public partial class BirthReport
{
//Not works well in web application.
private static BirthReportRepository repository = new BirthReportRepository();
public static BirthReport Method1()
{
return repository.SomeMethod();
}
public static BirthReport Method2()
{
return repository.SomeOtherMethod();
}
// Other methods(both static and instance) goes here.
}
Static mutable state is horrible. 静态可变状态是可怕的。 Period.
期。 The repository contains a context and a context contains tons of mutable states.
存储库包含一个上下文,并且上下文包含大量可变状态。 Besides that, contexts are supposed to have a short life cycle.
除此之外,上下文应该具有较短的生命周期。 And: I think that your domain classes should have nothing to do with repositories.
并且:我认为您的域类应该与存储库无关。 This is pseudo encapsulation.
这是伪封装。 Instead, let domain services handle Method1, method2.
而是让域服务处理Method1,method2。
You may consider using an IoC container to inject a context into your repositories and a repository into your domain services. 您可以考虑使用IoC容器将上下文注入到存储库中,并将存储库注入到域服务中。 The IoC container could also handle the life cycles of contexts and repositories.
IoC容器还可以处理上下文和存储库的生命周期。 For web, an instance per request is common.
对于Web,每个请求都有一个实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.