Get resolved dependancies of IRepository with AutoFac - c#

With interfaces set up like so:
public interface IRepository { };
public interface IFirstRepository : IRepository { };
public interface ISecondRepository : IRepository { };
public interface IThirdRepository : IRepository { };
And a Controller that needs some but not all of these repositories:
public class TestController : BaseController
{
private IFirstRepository mFirstRepository;
private ISecondRepository mSecondRepository;
// Standard DI for MVC
public TestController(IFirstRepository first, ISecondRepository second)
{
mFirstRepository = first;
mSecondRepository = second;
}
}
And BaseController looks like:
public class BaseController : Controller {
public IEnumerable<IRepository> GetRepos()
{
// One solution is to use reflection
// to get all properties that are IRepositories.
// Something along the lines of;
return typeof(this).GetProperties().Where(prop=>prop is IRepository);
// But is there a way to use the AutoFac context
// to get the repos, rather than use reflection?
// it surely already has that info since it
// was able to call the constructor correctly?
}
}
Is there a way BaseController can utilize the AutoFac context and existing info to get the collection of the IRepository instances requested by the TestController?
Autofac surely already has that info since it was able to call the constructor with the correct instances.
NB: The only reason I don't just use reflection here is performance concerns.

There's not an easy way to do this out of the box. If you find yourself in this situation, generally it means you have an interface design problem. There's an FAQ walking through an example of why this is, as well as some options.
If you really, really need to do this, then I'd probably look at adding metadata to each of the registrations where you have a metadata entry for each controller requiring that particular repository, then filter at the constructor using the metadata filter attribute. Again, the FAQ I mentioned walks through this and shows examples.
But if it was me working in this system... I'd step back and look at my interface design to see how to get away from needing this sort of filter in the first place. If they all can't be treated equally (Liskov substitution principle) then it indicates there are different interfaces required.

Related

Should we use an interface as dependency (in ctor) even if what we expect is one specific implementation?

Let's say we have a class, for example SqlIdProvider, that needs an SQL repository to perform some operations. We also have an SqlRepository class that implements an IRepository interface like follows:
public interface IRepository {
// All repository methods here.
}
public sealed class SqlRepository : IRepository {
// All repository methods here.
}
public sealed class SqlIdProvider {
private IRepository _repository;
public SqlIdProvider(IRepository repository){
_repository = repository;
}
}
The SqlIdProvider has a strong dependency on SqlRepository, so it will not work if I provide, for example, an instance of the following class:
public sealed class MongoRepository : IRepository {
// All repository methods here.
}
However, the signature of SqlIdProvider tells me that I could just provide one of these and everything should be fine.
In this situation, I usually think of three options:
1) Keep as is, and hope that the name will be enough for others to know that you shouldn't provide a MongoRepository to an SqlIdProvider (though not enforcing it in any way).
2) Change the SqlIdProvider constructor to take the concrete SqlRepository. This would enforce the requirement, but it would difficult unit testing, forcing us to remove the sealed keyword from SqlRepository to be able to fake the implementation (btw, I like classes to be sealed unless there's a good reason not to).
3) Create an empty interface that extends IRepository, designated for the sole purpose of SQL repositories, called ISqlRepository. Now, we could change the SqlIdProvider constructor to take the ISqlRepository interface instead.
public interface ISqlRepository : IRepository {
// This one is empty on purpose.
}
To me, option 3) seems to be the most appealing, however still feels a like I'm doing something wrong here by creating an empty interface.
Is there any better way we can be explicit with the constraint and at the same time allow easy unit testing?

Using constructor injection when caller expects a specific constructor signature

I'm new to DI in .NET C# & autofac and having problems to understand how to use DI when I can't fully control the caller side.
There are two scenarios I have problems to understand.
Scenario 1: Caller expects a default constructor (without any parameters)
How to handle this scenario when I still want to inject some Service Interfaces when the class is constructed? I was thinking of constructor chaining, but that would mean I have to know the concrete type and it works around the idea of DI. (at least I think).
public class ServiceWorker
{
IService _service;
public ServiceWorker(IService service)
{
_service = service
}
}
public class Caller
{
// No way to change this.
var serviceWorker = new ServiceWorker();
}
Scneario 2: Caller expects a specific constructor signature (e.g.
Same question here. How can I inject additional dependencies when the caller expects an exact match for the constructor signature?
I think my main issue in understanding the concept is, that I don't see how to do DI only partially when not everything is constructed by DI (caller)
public class ServiceWorker
{
IService _service;
public ServiceWorker(string name, string id, IService service)
{
_service = service
}
}
public class Caller
{
// No way to change this.
var serviceWorker = new ServiceWorker(name, id);
}
I know, this is pretty basic, but I believe I need to understand this first before moving on. Are there alternatives?
As Steven correctly points out in his comment, being restricted to a specific constructor signature is an instance of the Constrained Construction anti-pattern. Sometimes, however, that can be outside your control.
An example is the so-called 'Provider pattern', which isn't a pattern at all. In such an example, you may have to play by the rules of a third-party framework, so there isn't much you can do about it. Such frameworks should be considered unfriendly to Dependency Injection.
Consider scenario 2 in the OP, since scenario 1 is just a special case of scenario 2. If you must supply a class with a certain constructor, you could create a Facade that has the required constructor signature. This enables you to avoid polluting your well-designed classes that use Dependency Injection with the constraints imposed by the third-party framework. It could look like this:
public class ServiceWorker
{
IService _service;
public ServiceWorker(string name, string id, IService service)
{
_service = service
}
}
public class ServiceWorkerFacade
{
ServiceWorker imp;
public ServiceWorkerFacade(string name, string id)
{
imp =
new ServiceWorker(
name,
id,
new FooService(
new BarService(),
new BazService());
}
}
public class Caller
{
// No way to change this.
var serviceWorker = new ServiceWorkerFacade(name, id);
}
FooService implements IService. Just to make things interesting, I've assumed that FooService has dependencies of its own, and that those dependencies are satisfied by BarService and BazService.
As Steven suggests, then, you can (from necessity) consider the Facade's constructor the Composition Root.
If you have any opportunity to influence the design of the framework in question, you could point the developers to my guidance on designing DI-friendly frameworks.

Castle Windsor registering types

Im looking for an answer to what I suspect is a fairly basic question.
I am starting out using Windsor now and am struggling to figure out how to register an interface...
In my app I have an IRepository interface which is passed into my controllers in their constructors. I want Windsor to resolve these dependencies for me but am struggling to figure out how to do this.
So my IRepository looks a little like this:
public interface IRepository : IDisposable
{
List<string> GetList();
}
This is implemented in two classes:
public class Repository1 : IRepository
{
public List<string> GetList(){...}
}
public class Repository2 : IRepository
{
public List<string> GetList(){...}
}
My Controller looks a little like this:
public class HomeController : Controller
{
private readonly IRepository _repo;
public HomeController(IRepository repo)
{
_repo = repo;
}
...
Now I would like to register IRepository to resolve to either of the implementations Repository1 or Repository2 (Eventually I want to be able to figure out which Repository is availabe in other assemblies and load whichever is available)
Now, I have register the classes and change the constructor to take an instance of one of the classes and that works, but I want to do it against the interface... and thats where Im struggling.
I would also like this to be generic enough that if I have an IWhatever and a class that implements it that windsor would be able to resolve that too without having to register each and every one...
I have this (Which works)
container.Register(Classes.FromAssemblyContaining<Repository1>()
.BasedOn(typeof(IRepository))
.WithService.AllInterfaces()
.LifestyleTransient());
But its only registering Repository1... Any help appreciated, in the mean time Ill be back reading the documentation again and seeing if it sinks in this time!
Thanks
I think that what happens is that you are registering both your repositories, but since your controller only asks for one repository Windsor returns the first one by default.
What you could do to check whether the repositories is to call container.ResolveAll() just after registration; i think that you will get two results.
To correct this, either you must tell your controller that it must resolve a list of repositories (i.e. IRepository[]) or you must narrow down the repository type that is expected. For example if your controller was Controller<T> and your repositories were IRepository, the selection would occur depending on the type of T.
Found the answer:
http://mikehadlow.blogspot.co.uk/2010/01/10-advanced-windsor-tricks-2-auto.html?m=1
this is pretty much what i was looking for, thanks for the help everyone!

How to inject a dependency into a base class if child doesn't know it?

I have an abstract base class Command that depends on ICommandLogger interface:
public abstract class Command
{
public Command(ICommandLogger cmdLogger) { /* ... */ }
}
And now all the inheritors are look like:
public class ConcreteCommand : Command
{
public ConcreteCommand(CommandLoggersNamespace.ICommandLogger cmdLogger)
: base(cmdLogger)
{
}
}
I don't like they are forced to know about ICommandLogger (which they do not use).
How to get around of this? Or what are the reasons for complete redesign?
There's a problem in your design that causing you all this trouble. First of all, logging is a cross-cutting concern and you should prevent polluting classes with that. Second, if you let the base class implement logging, what is the next cross-cutting concern that will be added on the logger base class. The second you start adding another cross-cutting concern, the base class will violate the Single Responsibility Principle. Your base class will eventually grow to a big unmanageable class with lots of dependencies, and lot's of reasons to change.
Instead, try adding logging as a decorator. Your design however, prevents you from effectively doing that, since you will probably have dozens of concrete commands and they would all need their own decorator. But the core problem with your design is that you mix data and behavior. Let the command be nothing more than a class containing some data (DTO) and extra the commands logic into its own class; let's call that the command handler.
On top of that, let command handlers implement this interface:
public interface ICommandHandler<TCommand>
{
void Handle(TCommand command);
}
This will look like this:
public class MoveCustomerCommand
{
public Guid CustomerId;
public Address NewAddress;
}
public class MoveCustomerCommmandHandler : ICommandHandler<MoveCustomerCommand>
{
public void Handle(MoveCustomerCommand command)
{
// behavior here.
}
}
What's interesting about this design is that since all business logic is now hidden behind one narrow interface, and this interface is generic, it becomes very easy to extend the behavior of the system by wrapping handlers with decorators. For instance a logging decorator:
public class LoggingCommandHandlerDecorator<TCommand>
: ICommandHandler<TCommand>
{
private readonly ICommandHandler<TCommand> decoratee;
public LoggingCommandHandlerDecorator(
ICommandHandler<TCommand> decoratee, ILog log)
{
this.decoratee = decoratee;
this.log = log;
}
public void Handle(TCommand command)
{
this.log.Log("Executing " + typeof(TCommand).Name + ": " +
JsonConvert.Serialize(command));
try
{
this.decoratee.Handle(command);
}
catch (Exception ex)
{
this.log.Log(ex);
throw;
}
}
}
Since this LoggingCommandHandlerDecorator<TCommand> is generic, it can be wrapped around any ICommandHandler<TCommand>. This allows you to let consumers take a dependency on some ICommandHandler<TCommand> (such as ICommandHandler<MoveCustomerCommand>) and you can add crosscutting concerns to all business logic without changing a single line of code.
This will in most cases remove the need to use a base class completely.
You can read more about this type of design here.
If you are doing dependency injection via the constructor, there's no way around this. An alternative is dependency injection via property setters. Personally, I prefer the constructor method, because to me, that communicates that this class requires this dependency whereas a property-injected dependency communicates an optional dependency.
If you go the constructor route, and your base class takes a lot of dependencies, you can alleviate some of the pain by creating an aggregate service so that the base only needs one parameter injected instead of many.
If they don't use the command logger you may try to not set any at all, like this:
public ConcreteCommand()
: base(null)
{
}
If this does not work (throws an Exception) you may try to implement a phony command logger and instantiated that one:
public ConcreteCommand()
: base(new MyPhonyCommandLogger())
{
}
If you don't want those phony instances around, have a single instance statically available:
public ConcreteCommand()
: base(MyPhonyCommandLogger.Instance)
{
}
Well another way of looking at it is that the ConcreteComand class does have a dependency on ICommandLogger. It inherited it when it derived from Command.
Therefore there is no way around what you are doing that makes sense other than for ConcreteCommand to accept the dependency on behalf of its base class - think about it not in terms of "ConcreteCommand has a Command" but more like "ConcreteCommand is a Command"
Think about how you'd handle wanting to override the base class logging behaviour if you somehow were able to get he base class dependency on ICommandLogger to somehow "sneak past" the construction of ConcreteCommand...
If you want to be able to provide "base like" functionality (base.Log("foo")), etc) and you absolutely do not want ConcreteComand to know about ICommandLogger, then you can always switch to "has a" type scenario - whereby Command is just a member variable of ConcreteCommand (a silly reason approach in this case IMHO!)
I don't like they are forced to know about ICommandLogger (which they
do not use).
Well they do; unless you instantiate an object of type ICommandLogger in the abstract class and provide a parameterless constructor, you're currently forcing inheritors to know about it.

Should AggregateService be used as a container to store common dependencies?

I have a base controller class which uses aggregate services in autofac to inject its dependencies. In a class derived from base controller, I need to access a service which is a part of aggregate container. Which one is a better way?
public Interface ICommonControllerDependencies
{
ICookieService CookieService{ get; }
IAuthenticationService AuthenticationService{ get; }
}
public abstract class BaseController : Controller
{
protected readonly ICommonControllerDependencies Dependencies;
protected BaseController(ICommonControllerDependencies dependencies)
{
this.Dependencies = dependencies;
}
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.Controller.ViewData[UserName] = Dependencies.AuthenticationService.UserName;
base.OnActionExecuting(filterContext);
}
protected ActionResult RedirectToDefaultPage()
{
var page = Dependencies.CookieService.GetDefaultPageCookie(Request, RouteData);
//Do Something
}
}
public class BaseReportController : BaseController
{
public BaseReportController(ICommonControllerDependencies dependencies)
: base(dependencies)
{
_cookieService = dependencies.CookieService;
}
}
OR
public class BaseReportController : BaseController
{
public BaseReportController(
ICookieService cookieService,
ICommonControllerDependencies dependencies)
: base(dependencies)
{
_cookieService = cookieService;
}
}
The AggregateService is intended to be what isolates your subclass from changes in the super class, and enable changes in the superclass without breaking subclasses.
If you go for option 1, you couple the subclass to your superclass, thus loosing the intended isolation.
Without knowing more about your design I would go for option 2. I don't think that I can anticipate ServiceA to always be there. Taking an explicit dependency on IServiceA in the subclass, that class can live on happily ignorant about changes going on in the superclass internals.
When you need an Aggregate Service (as the Autofac documentation calls it), this could be a sign of violating the Single Responsibility Principle, that states that a class should do one thing, and only one thing.
In other words, the Aggregate Service pattern is a code smell*.
Having big base classes is a code smell as well, since base classes tend to grow and grow to big and complicated classes, that contain a lot of code that not all sub types use. Instead, the general advice is to favor composition over inheritance.
With UI frameworks such as ASP.NET MVC however, this is not always easy, since most frameworks themselves promote inheritance.
Try to extract the logic of the base class to separate dependencies, especially when that code in the base class isn't used by all sub types. For instance, you might be able to refactor the RedirectToDefaultPage method to the following:
public class DefaultPageRedirector
{
private readonly ICookieService cookieService;
public DefaultPageRedirector(ICookieService cookieService)
{
this.cookieService = cookieService;
}
public ActionResult RedirectToDefaultPage(
Controller controller)
{
var page = this.cookieService.GetDefaultPageCookie(
controller.Request, controller.RouteData);
//Do Something
}
}
This way you can inject the DefaultPageRedirector only into Controller types that actually need it.
For the OnActionExecuting it is different, since it gets called for each and every sub type. However, the ViewData["UserName"] property will probably not be used by every View in the system and in that case you should consider returning the UserName as part of the (staticly typed) ViewModel object. If it is used by most views, you might want to consider using a partial view, because you might have some repetitive code in your views (The DRY principle holds not only for code, but for every part in the system).
This will probably get rid of most code in the base class, which probably also removes most of the dependencies in the base (if not all).
* Note that a code smell doesn't mean there is always a problem. To quote Wikipedia: "code smell is any symptom in the source code of a program that possibly indicates a deeper problem."
I would think that it depends on whether you have IserviceA registered in the container or not and how you anticipate your design evolving.
Personally, I would go with the first option if you don't anticipate removing serviceA from the ICommonControllerDependencies interface. It just seems simpler to inject a single interface. If you think that you may remove serviceA at some time, I would consider going with the second option as it removes the coupling between the service and the controller dependencies within the BaseReportController. I think the second option more closely follows the Law of Demeter.

Categories

Resources