Autofac - 生命周期和模块 [英] Autofac - Lifetime and modules

查看:60
本文介绍了Autofac - 生命周期和模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题(抽象)

给定一个注册依赖项 X 的模块.依赖项 X 在 MVC3 应用程序中具有不同的生命周期(每个 HttpRequest 的生命周期),然后在控制台应用程序中(每个生命周期范围的依赖项具有名称).在哪里或如何指定依赖项 X 的生命周期?

Given a module which registers dependency X. The dependency X has a different lifetime in a MVC3 app (lifetime per HttpRequest) then in a console application (dependency per lifetimescope with a name). Where or how to specify the lifetime of dependency X?

案例

我已将所有与数据库相关的代码放在一个程序集中,其中有一个模块可以注册所有存储库.现在ISession(Nhibernate)注册也在模块中.

I've put all my database related code in a assembly with a module in it which registers all repositories. Now the ISession (Nhibernate) registration is also in the module.

ISession 是依赖项 X(在给定的问题案例中).ISession 在 MVC3 应用程序中具有不同的生命周期(每个请求的生命周期),然后在我定义命名生命周期范围的控制台应用程序中具有不同的生命周期.

ISession is dependency X (in the given problem case). ISession has different lifetime in a MVC3 app (lifetime per request) then in a console app where I define a named lifetimescope.

ISession的注册应该在模块外吗?会很奇怪,因为它是一个实现细节.

Should the registration of ISession be outside the module? Would be strange since it's an implementation detail.

这里最好的情况是什么?设计缺陷或是否有针对此的智能结构:)?

What is the best case to do here? Design flaw or are there smart constructions for this :) ?

推荐答案

根据您的用例描述,我认为您有几个选择.

Given your use case description, I'd say you have a few of options.

首先,您可以让每个应用程序注册自己的一组依赖项,包括生命周期范围.考虑到应用程序之间的差异以及注册看起来相当小的事实,在这方面拥有一两段重复"代码并不是什么大问题.

First, you could just have each application register their own set of dependencies including lifetime scope. Having one or two "duplicate" pieces of code in this respect isn't that big of a deal considering the differences between the application and the fact that the registrations appear fairly small.

其次,您可以将公共部分(减去生命周期范围)包装到可以在每个应用程序中使用的 ContainerBuilder 扩展方法中.这仍然意味着每个应用程序都有一些重复代码",但公共逻辑将包含在一个简单的扩展中.

Second, you could wrap the common part (minus lifetime scope) into a ContainerBuilder extension method that could be used in each application. It would still mean each app has a little "duplicate code" but the common logic would be wrapped in a simple extension.

public static IRegistrationBuilder<TLimit, ScanningActivatorData, DynamicRegistrationStyle>
  RegisterConnection<TLimit, ScanningActivatorData, DynamicRegistrationStyle>(this ContainerBuilder builder)
{
  // Put the common logic here:
  builder.Register(...).AsImplementedInterfaces();
}

在每个应用中使用这样的扩展程序看起来像:

Consuming such an extension in each app would look like:

builder.RegisterConnection().InstancePerHttpRequest();
// or
builder.RegisterConnection().InstancePerLifetimeScope();

最后,如果您知道它是网络还是非网络,您可以制作一个自定义模块来处理开关:

Finally, if you know it's either web or non-web, you could make a custom module that handles the switch:

public class ConnectionModule : Autofac.Module
{
  bool _isWeb;
  public ConnectionModule(bool isWeb)
  {
    this._isWeb = isWeb;
  }

  protected override void Load(ContainerBuilder builder)
  {
    var reg = builder.Register(...).AsImplementedInterfaces();
    if(this._isWeb)
    {
      reg.InstancePerHttpRequest();
    }
    else
    {
      reg.InstancePerLifetimeScope();
    }
  }
}

在每个应用程序中,您都可以注册模块:

In each application, you could then register the module:

// Web application:
builder.RegisterModule(new ConnectionModule(true));

// Non-web application:
builder.RegisterModule(new ConnectionModule(false));

或者,您提到您在其他应用中的生命周期范围有一个名称.你可以让你的模块取这个名字:

Alternatively, you mentioned your lifetime scope in your other apps has a name. You could make your module take the name:

public class ConnectionModule : Autofac.Module
{
  object _scopeTag;
  public ConnectionModule(object scopeTag)
  {
    this._scopeTag = scopeTag;
  }

  protected override void Load(ContainerBuilder builder)
  {
    var reg = builder.Register(...)
                     .AsImplementedInterfaces()
                     .InstancePerMatchingLifetimeScope(this._scopeTag);
  }
}

消费类似:

// Web application (using the standard tag normally provided):
builder.RegisterModule(new ConnectionModule("httpRequest"));

// Non-web application (using your custom scope name):
builder.RegisterModule(new ConnectionModule("yourOtherScopeName"));

我建议不要在 Web 应用程序中简单地使用 InstancePerLifetimeScope,除非这确实是您的意图. 正如其他答案/评论中所述,InstancePerHttpRequest 使用特定的命名生命周期范围,以便创建子生命周期范围是安全的;使用InstancePerLifetimeScope 没有这样的限制,所以实际上每个子作用域只有一个连接,而不是请求的一个连接.我个人不认为其他开发人员不会使用子生命周期范围(这是推荐的做法),所以在我的应用程序中我非常具体.如果您完全控制自己的应用程序,并且可以确保不会创建额外的子作用域,或者您确实希望每个作用域有一个连接,那么 InstancePerLifetimeScope 可能会解决您的问题.

I would recommend against simply using InstancePerLifetimeScope in a web application unless that's actually what you intend. As noted in other answers/comments, InstancePerHttpRequest uses a specific named lifetime scope so that it's safe to create child lifetime scopes; using InstancePerLifetimeScope doesn't have such a restriction so you'll actually get one connection per child scope rather than one connection for the request. I, personally, don't assume that other developers won't make use of child lifetime scopes (which is a recommended practice), so in my applications I'm very specific. If you're in total control of your application and you can assure that you aren't creating additional child scopes or that you actually do want one connection per scope, then maybe InstancePerLifetimeScope will solve your problem.

这篇关于Autofac - 生命周期和模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆