I recently added support for ASP.NET Core to my Tact.NET IOC Container, and I thought that I would share some of the interesting requirements I discovered while doing so. I had originally expected the default ASP.NET Core container would follow the same rules as the official Microsoft Unity container, but that turned out not to be the case!
1) Register is first in win.
The Unity container was last in win, and it would completely disregard the original registration. With ASP.NET Core you need to preserve the original registration and then treat all subsequent registrations as addition registrations that will only be resolved when ResolveAll is invoked, similar to keyed registrations in Unity. Which brings us to our next difference...
public class RegisterIsFirstInWinTests
{
[Fact]
public void Unity()
{
var log = new EmptyLog();
using (var container = new TactContainer(log))
{
container.RegisterSingleton<IExample, ExampleA>();
container.RegisterSingleton<IExample, ExampleB>();
var example = container.Resolve<IExample>();
Assert.IsType<ExampleB>(example);
}
}
[Fact]
public void AspNetCore()
{
var log = new EmptyLog();
using (var container = new AspNetCoreContainer(log))
{
container.RegisterSingleton<IExample, ExampleA>();
container.RegisterSingleton<IExample, ExampleB>();
var example = container.Resolve<IExample>();
Assert.IsType<ExampleA>(example);
}
}
public interface IExample
{
string Name { get; }
}
public class ExampleA : IExample
{
public string Name => nameof(ExampleA);
}
public class ExampleB : IExample
{
public string Name => nameof(ExampleB);
}
}