I have two classes that take a ILastActivityUpdator
as a constructor parameter: UserService
and AnonymousUserService
.
Autofac is nicely documented and it looks like you can find what you are after here. From what I can tell, if you have registered your updators with
builder.RegisterType<LastActivityUpdator>();
builder.RegisterType<AnonymousUserLastActivityUpdator>();
then you should be able to register your services with
builder.Register(c => new UserService(c.Resolve<LastActivityUpdator>()));
builder.Register(c => new AnonymousUserService(c.Resolve<AnonymousUserLastActivityUpdator>()));
or
builder.RegisterType<UserService>().WithParameter(
(p, c) => p.ParameterType == typeof(ILastActivityUpdator),
(p, c) => c.Resolve<LastActivityUpdator>());
builder.RegisterType<AnonymousUserService>().WithParameter(
(p, c) => p.ParameterType == typeof(ILastActivityUpdator),
(p, c) => c.Resolve<AnonymousUserLastActivityUpdator>());
Then when you resolve UserService
or AnonymousUserService
from the container, they will get the correct dependencies.
As an aside, if an interface is injected into a class, then that class should function correctly with all implementations of that interface (LSP). From the class names, it looks like AnonymousUserService
only works with AnonymousUserLastActivityUpdator
and not any implementation of ILastActivityUpdator
. If that is the case, then it might be appropriate to introduce a different abstraction (like IAnonymousUserLastActivityUpdator
) as you suggested.