问题
I'm currently testing Autofac for our company.
We'd like to have the following rules:
If an interface has been implemented only once, then add it automatically using the builder.RegisterAssemblyTypes (see below).
Otherwise, we need to make sure to manually write the rule that will decide which implementation is the 'default' implementation.
I have the following code:
var builder = new ContainerBuilder();
builder.RegisterAssemblyTypes(Assembly
.Load("Lunch.Service")).As(t => t.GetInterfaces()[0]);
builder.RegisterType<ConsoleLoggerService>()
.As<ILoggerService>().SingleInstance();
builder.RegisterModule(new DestinationModule());
builder.RegisterType<TransportationService>()
.As<ITransportationService>().PropertiesAutowired();
Right now, it's working, but it decides which the first implementation is and will automatically create that. We'd like to make that a manual process and have an error thrown if we don't manually create the 'rule'. Is this possible?
回答1:
You could do something like this:
cb.RegisterAssemblyTypes(assembly).Where(type =>
{
var implementations = type.GetInterfaces();
if (implementations.Length > 0)
{
var iface = implementations[0];
var implementers =
from t in assembly.GetTypes()
where t.GetInterfaces().Contains(iface)
select t;
return implementers.Count() == 1;
}
return false;
})
.As(t => t.GetInterfaces()[0]);
This will register all implementations where only a single implementer exists, and ignore interfaces with multiple implementations so you can register them manually. Note that I don't claim this is efficient in any way (depending on the number of services, you may want to look at caching implementers for example).
来源:https://stackoverflow.com/questions/10486342/would-like-autofac-to-not-register-any-interface-that-has-more-than-one-implemen