控制器实例创建和销毁的MVC中的每一个请求 - 的WebAPI - 什么范围的依赖注入?控制器、实例、范围、MVC

2023-09-05 03:22:47 作者:本人特价

我开发一个的WebAPI 应用程序。

和我的理解的WebAPI MVC 每一个请求时,一时间该API - 控制器的新实例被创建,它被设置在请求送达后

此外,注入的依赖我用城堡温莎

Also, to inject dependency I use castle-windsor.

     aContainer.Register(Component
        .For<IDataProvider>()
        .ImplementedBy<DataProvider>()
        .LifestyleScoped());

    aContainer.Register(Component
        .For<IDataProvider>()
        .ImplementedBy<DataProvider>()
        .LifestylePerWebRequest());

这里的问题是我很迷茫,使用 LifeStyleScoped LifeStylePerRequest 。该文档是pretty的广阔,我失去了。

The question here is I am very confused with using LifeStyleScoped and LifeStylePerRequest. The documentation is pretty vast and I am lost.

谁能告诉我什么是在的WebAPI 环境中使用他们每个人的影响?

Can anyone tell me whats the impact of using each of them in a WebAPI context ?

推荐答案

如果你再想想网络堆栈之外,你会看到,LifeStyleScoped没有混淆的。它只是标志着开始和object`s生命周期的结束。我已经看到实施的UnitOfWork模式与范围的生命周期提供了一个功能像滚嵌套事务回 - 工作嵌套的单位 - 或多个相同的请求/动作时

If you try to think outside of the Web stack you will see that LifeStyleScoped is not confusing at all. It just marks the begin and the end of an object`s lifecycle. I have seen implementation of UnitOfWork pattern with scoped lifetime which provides a capability like nested transactions with roll back - nested units of work - or multiple during the same request/action.

LifestylePerWebRequest是控制器的默认生活方式 - 你不希望你的控制器更活那么这个请求,因为他们在那里只是为了满足你的要求,仅此而已。

LifestylePerWebRequest is the default lifestyle of Controllers - you do not want your Controllers to live more then the request, because they are there just to serve your request and nothing more.

您可以注入任何你想要成为一个控制器。当然,你必须小心,释放你的组件。例如 - 你让单身的生活方式实现IMyService,并注入到控制器(如果您在注射服务为私有成员,那么他们将是线程安全的一点,因为他们的方法栈帧是每一个方法调用不同)。这样,您将不得不为每个请求IMyService的同一个实例。在应用程序的生命周期或者其他程序结束事件中,你必须释放一切的结束。尤其是SQL连接。

You can inject whatever you want into a Controller. Of course you must take care to release your components. For example - You make singleton lifestyle implementation of IMyService and inject it into the Controller (If you make the injected services as private members then they will be thread safe too because their method stack frame is different for every method call). This way you will have the same instance of IMyService for every request. At the end of the app lifecycle or other 'application end' event you must release everything. Especially SQL connections.

如果你再往下对象分辨率图借此它可能会变成你有IUnitOfWork已范围的寿命和你做,并IMyService.DoTheJob在处理其中有几个();

If you take this further down the object resolution graph it may turn out that you have IUnitOfWork which has scoped lifetime and you make and dispose several of them during IMyService.DoTheJob();

作为一个结论 - 你可能会注入任何你想要进入你的控制器,但记得要释放一些有更大的寿命范围,那么PerWebRequest和特定请求之后不需要的对象

As a conclusion - you may inject whatever you want into your controller but remember to release some of the objects that have "greater lifetime scope" then PerWebRequest and are not needed after the particular request.