1

在一个应用程序中,我有以下组件(除其他外):

  • MyDbContext:实体框架数据访问
  • DBResourceProviderFactoryResourceProviderFactory提供自定义的自定义IResourceProvider(称为DBResourceProvider...)
  • 其他服务
  • 结构图

自定义资源提供程序正在使用 db 查找资源,注入方式与此 SO 答案MyDbContext中的描述类似。

MyDbContext也用于各种其他服务,并且由于它是一个 Web 应用程序,因此我使用 StructureMaps方法HttpContextScoped将生命周期限制为MyDbContext请求的生命周期(请参阅另一个 SO 问题及其关于此主题的答案):

x.For<MyDbContext>().HttpContextScoped();

但是,似乎 an 的生命周期IResourceProvider并不限于单个 http 请求。因此,DBResourceProvider一直挂在一个MyDbContext将在第一次请求后处理的引用上。

如何处理这种生命周期不匹配- 让 StructureMap在将 HttpContext 范围内的实例返回给所有其他服务时返回MyDbContext瞬态?IDbResourceProvider

我需要两种不同的实现吗?标记界面?还是首先使用实体​​框架查找本地化资源(性能等)是个坏主意?

4

1 回答 1

1

If you have a service that has (or needs to have) a long lifetime than (one of) its dependencies, the general solution is to use a factory to get those dependencies.

In your situation the solution might be simple. When your DBResourceProvider is defined in your composition root of your MVC application, it would simply succeed to use the DependencyResolver.Current.GetService method to get the MyDbContext.

When the DBResourceProvider service isn't part of the composition root (for instance because it contains business logic that you need to test), you could either extract that logic into its own class, to allow the service to be in the composition root, or you can inject a (singleton) factory (for instance IDbContextFactory or Func<MyDbContext>) that allows you to get the proper instance to be resolved.

于 2012-11-08T10:52:10.673 回答