MarimerLLC / csla

A home for your business logic in any .NET application.
https://cslanet.com
MIT License
1.23k stars 394 forks source link

Cannot change ContextManager through CslaOptions.ContextManagerType #4047

Closed mirecg closed 1 week ago

mirecg commented 2 weeks ago

Describe the bug I'm not able to change ContextManager using CslaOptions.ContextManagerType in AddCsla() extension method, but I have to explicitly add it to the ServiceCollection of AppBuilder before AddCsla() method is called.

This is because of this order of execution in AddCsla method. At first it registers default ContextManagers into a ServiceCollection and after that it registers the one given in CslaOptions.ContextManagerType: https://github.com/MarimerLLC/csla/blob/d6069d465041fdc687bc7a46602540754d56f8c8/Source/Csla/Configuration/ConfigurationExtensions.cs#L48-L50 Consequently ApplicationContextAccessor gets both of them, but selects the first valid ContextManager, which is the default one and not the one that was specified in CslaOptions.ContextManagerType. https://github.com/MarimerLLC/csla/blob/d6069d465041fdc687bc7a46602540754d56f8c8/Source/Csla/Core/ApplicationContextAccessor.cs#L34-L41

Version and Platform CSLA version: 8.2.3 OS: Windows Platform: .NET 8.0

Code that Fails

var builder = Host.CreateApplicationBuilder();

builder.Services.AddCsla((c) => c.ContextManagerType = typeof(ApplicationContextManagerTls));
var host = builder.Build();

var appContextAccessor = serviceProvider.GetRequiredService<ApplicationContextAccessor>();
var contextManager = appContextAccessor.GetContextManager();
// this is false, should be true
var isContextManagerTls = contextManager.GetType() == typeof(ApplicationContextManagerTls);
// this is true, should be false
var isContextManagerDefault = contextManager.GetType() == typeof(ApplicationContextManager);

If I register the ContextManager this way, it will work:

builder.Services.AddScoped<Csla.Core.IContextManager, ApplicationContextManagerTls>();
builder.Services.AddCsla();

Stack Trace or Exception Detail

Additional context

rockfordlhotka commented 1 week ago

@mirecg I think you are not blocked now?

I have fixed the code in v8.x and main, but won't immediately push the v8 fix to NuGet if you are able to move forward?

mirecg commented 1 week ago

No, I'm not, thank you.