2

What lifestyle should be used to replace PerWebRequest when using the Castle Windsor MS Adapter?

https://github.com/volosoft/castle-windsor-ms-adapter

Before dotnet core I would use the PerWebRequest lifestyle for almost all of the components in the container. Now that we are disconnected from IIS modules and http context, I want to ensure my components are being created and disposed when the web requests starts and ends.

Example:

container.Register(Component.For<MyEntityFrameworkContext>)
    .ImplementedBy<MyEntityFrameworkContext>()
    .LifestyleTransient());
Steven
  • 166,672
  • 24
  • 332
  • 435
detroitpro
  • 3,853
  • 4
  • 35
  • 64

1 Answers1

2

ASP.NET Core has it's own 'scoped' lifecycle, which is 'per request'. See it's documentation: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection

Usage example:

services.AddScoped<ICharacterRepository, CharacterRepository>();

You should do it inside ConfigureServices method in Startup class.

hikalkan
  • 2,234
  • 15
  • 17
  • Is there any way to decouple from using the built in IoC container? We have multiple `endpoints` in this project and want to use a single container with a little more power. – detroitpro Nov 14 '16 at 19:00
  • Also, if we must use the built in container, what are the situations where we would use adapters such as this? – detroitpro Nov 14 '16 at 19:01
  • This is the design of AspNet Core's DI. But you can use LifestyleCustom to make it directly with Windsor API (this library makes it here: https://github.com/volosoft/castle-windsor-ms-adapter/blob/master/src/Castle.Windsor.MsDependencyInjection/WindsorRegistrationHelper.cs#L105). – hikalkan Nov 14 '16 at 19:11
  • If you have multiple place to register dependencies, you have to do that abstraction yourself. Example: You can create an interface to register dependencies, find all implementations in ConfigureServices and call them. – hikalkan Nov 14 '16 at 19:13
  • Is it correct to say that the registrations in this gist provide the same functionality? https://gist.github.com/detroitpro/d6f05342f6b9817ed3269b0a6449c957 – detroitpro Nov 14 '16 at 19:26
  • Yes, it has the same functionality. – hikalkan Nov 15 '16 at 16:46
  • using LifestyleCustom didn't work for me in ASP.NET Core. Castle resolved new transient instance instead of scoped instance (in https://github.com/volosoft/castle-windsor-ms-adapter/blob/master/src/Castle.Windsor.MsDependencyInjection/MsScopedLifestyleManager.cs, it used "//Act as transient!" path). After some digging, I used not-yet-released Castle Windsor implementation - https://github.com/fir3pho3nixx/Windsor/blob/aspnet-core-windsor-final/docs/aspnetcore-facility.md (as of now you need to build castle windsor - git branch aspnet-core-windsor-final). – xhafan May 25 '18 at 14:06