I have the following test
[TestFixture]
public class Test
{
public interface IMy { }
class MyClass : IMy { }
class MyClass2 : IMy { }
[Test]
public static void Go()
{
var builder = new ContainerBuilder();
builder.RegisterType<MyClass>().AsImplementedInterfaces();
builder.RegisterType<MyClass2>().AsImplementedInterfaces();
var container = builder.Build();
var resolved = container.Resolve<IMy>();
Console.WriteLine(resolved);
}
}
Why it does not throw exception when implementations are obviously in conflict ? And how to make it throw exception if such a conflict found ?
UPDATE Solution with registration checking is almost Ok, but there is simple situation when it fails:
[TestFixture]
public class Test
{
public interface IPlugin
{
}
public interface IMy
{
}
class MyClass : IMy, IPlugin
{
public void Dispose()
{
}
}
class MyClass2 : IPlugin
{
public void Dispose()
{
}
}
public class SingleRegistrationModule : Module
{
protected override void AttachToComponentRegistration(
IComponentRegistry componentRegistry,
IComponentRegistration registration)
{
foreach (var service in registration.Services)
{
var registrations = componentRegistry.RegistrationsFor(service);
if (registrations.Count() > 1)
{
throw new Exception(
"Can't register '{registration.Activator.LimitType}' as '{service}'" +
" because '{registrations.First().Activator.LimitType}' is already registered");
}
}
}
}
[Test]
public static void Go()
{
var builder = new ContainerBuilder();
builder.RegisterType<MyClass>().AsImplementedInterfaces();
builder.RegisterType<MyClass2>().AsImplementedInterfaces();
builder.RegisterModule<SingleRegistrationModule>();
var container = builder.Build();
var resolved = container.Resolve<IMy>();
Console.WriteLine(resolved);
}
}
In this case nobody resolves IInitializable so it is acceptable to have multiple implementations. Moreover there are scenarios when mulltiple implementation is OK, for example IPluginToSomething