alternative for System.Web.Hosting.HostingEnvironment.RegisterObject in asp.net core 2.0

时间:2017-12-18 06:33:43

标签: c# asp.net asp.net-mvc asp.net-core-2.0

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

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.

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.

1 个答案:

答案 0 :(得分:1)

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.

And ApplicationStopped:

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

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
}

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.

相关问题