asp.net core 2.0中System.Web.Hosting.HostingEnvironment.RegisterObject的替代方法 [英] alternative for System.Web.Hosting.HostingEnvironment.RegisterObject in asp.net core 2.0

查看:521
本文介绍了asp.net core 2.0中System.Web.Hosting.HostingEnvironment.RegisterObject的替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用HostingEnivronment.RegisterObject的旧版应用程序.

I have a legacy application where HostingEnivronment.RegisterObject is used.

我的任务是将其转换为asp.net core 2.0.但是,我无法在asp.net core 2.0中找到实现此方法或找到替代方法的方法.

I have been tasked with converting this to asp.net core 2.0. however I am unable to find a way to either implement this or find an alternative to this in asp.net core 2.0.

名称空间 Microsoft.AspNetCore.Hosting.Internal 不包含registerobject方法,也不具有IRegisteredObject接口.我对如何实现此功能一无所知.

the namespace Microsoft.AspNetCore.Hosting.Internal does not contain the registerobject method nor does it have the IRegisteredObject interface. I am at a loss on how to get this implemented.

推荐答案

在asp.net核心中实现类似目标的方法是使用

The way to achieve similar goal in asp.net core is to use IApplicationLifetime interface. It has two properties two CancellationTokens,

ApplicationStopping:

主机正在正常关闭.请求可能仍然是 加工.关机将阻止,直到此事件完成为止.

The host is performing a graceful shutdown. Requests may still be processing. Shutdown blocks until this event completes.

ApplicationStopped:

主机正在正常关闭.所有要求都应该是 完全处理.关机将阻止,直到此事件完成为止.

The host is completing a graceful shutdown. All requests should be completely processed. Shutdown blocks until this event completes.

此接口默认情况下已在容器中注册,因此您可以随时将其注入.您以前致电RegisterObject的地方,而是致电了

This interface is by default registered in container, so you can just inject it wherever you need. Where you previously called RegisterObject, you instead call

// or ApplicationStopped
var token = lifeTime.ApplicationStopping.Register(OnApplicationStopping);

private void OnApplicationStopping() {
     // will be executed on host shutting down
}

,并且OnApplicationStopping回调将在主机关闭时由运行时调用.以前调用UnregisterObject的地方,只需处理从CancellationToken.Register返回的令牌:

And your OnApplicationStopping callback will be invoked by runtime on host shutdown. Where you previously would call UnregisterObject, you just dispose token returned from CancellationToken.Register:

token.Dispose();

您还可以将这些取消令牌传递给需要取消令牌的操作,并且这些操作不应因关机而意外中断.

You can also pass these cancellation tokens to operations that expect cancellation tokens and which should not be accidentally interrupted by shutdown.

这篇关于asp.net core 2.0中System.Web.Hosting.HostingEnvironment.RegisterObject的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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