Define Default constructor Structuremap in a Generic Repository - asp.net-mvc

I have a generic IRepository that has 2 constructors, one have none parameters, other has the datacontext as parameter.
I want to define to structuremap to aways in this case use the parameterless constructor.
I want a way to create a parameterless contructor, other solutions that I have seen, they create a new Datacontext and pass it to the constructor that has parameters.

By default, StructureMap will use the constructor with the most arguments. In your case, since you want it to use the parameterless constructor, use the DefaultConstructorAttribute:
[DefaultConstructor]
public void Repository<T>() { }
public void Repository<T>(DataContext dataContext) { }

Related

How to decorate an ASP.NET MVC controller with Simple Injector

I'd like to apply some cross-cutting concerns to my MVC controllers. At the moment, this is implemented through an abstract base class, but as we are refactoring more of the code base to take advantage of dependency injection, I'm wondering if this is something Simple Injector can help me with through its decoration or interception facilities.
So I've attempted to create a pretty basic decorator:
public class ControllerDecorator : IController
{
private readonly IController _controller;
public ControllerDecorator(IController controller)
{
_controller = controller;
}
public void Execute(RequestContext requestContext)
{
// Do something of a cross-cutting nature here...
_controller.Execute(requestContext);
}
}
And in my composition root: container.RegisterDecorator<IController, ControllerDecorator>()
However, the code in my decorator's Execute method doesn't seem to ever get called. Is it because the MVC framework directly resolves my controller classes instead of going through IController? In that case, what can I do? What am I missing here?
In the default configuration, you can't apply decorators to controllers. The reason for this is that MVC's DefaultControllerFactory requests controllers by their concrete type. Because it requests a concrete type, Simple Injector is unable to apply a decorator; it has to assume that the caller needs this concrete type and has to therefore return this exact type (or a sub type).
To fix this, you will have to replace the default DefaultControllerFactory with a custom one:
public class SimpleInjectorControllerFactory : DefaultControllerFactory {
public IDictionary<Type, InstanceProducer> Producers { get; set; }
protected override IController GetControllerInstance(RequestContext rc, Type type) {
return (IController)this.Producers[type].GetInstance();
}
}
Next, in your bootstrapper, you'll have to replace the call to RegisterMvcControllers with the following:
var controllerTypes = SimpleInjectorMvcExtensions.GetControllerTypesToRegister(
container, Assembly.GetExecutingAssembly());
var controllerProducers = controllerTypes
.ToDictionary(type => type, type => CreateControllerProducer(container, type));
// Verify after creating the controller producers.
container.Verify();
ControllerBuilder.Current.SetControllerFactory(
new SimpleInjectorControllerFactory { Producers = controllerProducers });
The CreateControllerProducer method looks as follows:
private static InstanceProducer CreateControllerProducer(Container c, Type type) {
var producer = Lifestyle.Transient.CreateProducer(typeof(IController), type, c);
producer.Registration.SuppressDiagnosticWarning(
DiagnosticType.DisposableTransientComponent,
"MVC disposes the controller when the web request ends.");
return producer;
}
The crucial part is that the call to CreateProducer is supplied with typeof(IController); this allows Simple Injector to apply a decorator for IController.
This is it; now you can register your decorator for IController.
One warning though: with both Web API and the new ASP.NET core it is impossible to apply decorators to controllers. Both frameworks expect concrete types; they will break if you wrap the real controller. The preferred way with those frameworks to decorate controllers is through the OWIN pipeline. So this answer solely works with MVC 3, 4 and 5.

fakeiteasy initializing private members in constructor

I want to test methods in my controller, I know about this...
myController = new MyController();
A.CallTo(()=>myController.SomeMethodIWantToTest().Returns(someValueIAmTesting);
The problem is that inside that parameterless constructor, I call numerous methods in other assemblies that set values for private members,
public class MyController : Controller {
private ILoginBusiness loginBusiness;
private ISomethingElse somethingElse;
//... and so on...
public MyController(){
loginbusiness = ServiceFactory.GetLoginBusiness();
somethingElse = //some method in another assembly that initializes the value
//... and so on, calling methods in other assemblies that initialize the private members...
}
public ActionResult SomeMethodIWantToTest(){ }
}
So how do I isolate all those method calls in my constructor (so I'm not calling methods in those other assemblies?)
First,
myController = new MyController();
A.CallTo(()=>myController.SomeMethodIWantToTest().Returns(someValueIAmTesting);
Will result in an error, as A.CallTo only handles calls to fakes (and there should be an extra ) after …ToTest()).
Second, the general approach that is taken in this sort of situation is called Dependency Injection. Instead of having a class make all its dependencies (in your case, by calling methods from other assemblies), you have its dependencies provided to it.
Assuming you're able to start injecting dependencies, you're almost home. You're already relying on interfaces inside MyController, so then you can use FakeItEasy to supply fakes to MyController, avoiding calls to the out-of-assembly methods.

.NET MVC Service layer constructor

I'm interested how to implement my constructor in services. I'm a bit new to .NET so don't get me wrong if question is too trivial.
This are my current constructors but I would like to fully understand (since it looks like its working, I took code from somewhere)
// initialize UnitOfWork
private IUnitOfWork _unitOfWork;
public TownService()
: this(new UnitOfWork())
{
}
public TownService(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
What does : this means and which one is called first? Also I saw there is constructor with : base but I think thats the one thats calling superclass first.
Do I need to call new UnitOfWork() ? Isn't UnitOfWork supposed to be factory (shared) instance? Or it is factory and new UnitOfWork is not creating new but taking initialized one from memory?
Thanks.
Constructors in C#
Given your code
public TownService()
: this(new UnitOfWork())
{
//1
}
public TownService(IUnitOfWork unitOfWork)
{
//2
_unitOfWork = unitOfWork;
}
Invoking new TownService() will
Call the parameterless-constructor
Instantiate a new UnitOfWork and call the overload TownService(IUnitOfWork unitOfWork), so //2 is executed. This happens because of the this(...) call.
Then execute the parameterless constructor's body, i.e. //1
You need to get an instance of IUnitOfWork from somewhere, but calling the parameterless constructor which in turn will instantiate a new UnitOfWork probably isn't what you want - it doesn't really buy you much flexibility.
Using a factory
If you want to use a factory, you would go something like
ITownService s = new TownService(myFactory.Get<IUnitOfWork>());
thus avoiding the parameterless constructor.
Using IoC
If you want to use an IoC container, you would probably go something like this to configure your container
myContainer.Register<IUnitOfWork, UnitOfWork>(); //May need to provide database transaction or whatever
myContainer.Register<ITownService, TownService>();
You would also need to tell ASP.NET MVC to use the container when creating controllers. You do this by creating a ControllerFactory that is aware of your IoC container. Most IoC containers come with such a factory and instructions on how to use it.
Once that is done, you would be able to declare your controllers like
public class MyController
{
public MyController(ITownService townService)
{
/*...*/
}
}
and have ASP.NET MVC and your IoC container do the rest.

Constructor injection with Func on Ninject

I'm using a Ninject module to bind different types to their corresponding interfaces.
Injection will take place inside a class's constructor. The problem is that the class has another constructor with a signature including Func.
Ninject is confused and throws this at me:
Error activating ClassTest using implicit self-binding of ClassTest. Several constructors have the same priority. Please specify the constructor using ToConstructor syntax or add an Inject attribute.
See below how the binding is done and how I do the injection:
this.Bind<InterfaceA>().To<ClassA>();
...
public class ClassTest
{
public ClassTest(InterfaceA a)
{
}
public ClassTest(Func<ClassB> funcB)
{
}
}
...
var giveMeTest = kernel.Get<ClassTest>(); // exception thrown
}
It seems that Func is the culprit here, can you please explain me why Ninject gets confused?
Thanks
Best you delete all unused constructors. There is no reason for adding constructors that are never used. If you really need multiple constructors then you have to tell Ninject which one to pick, e.g.:
Bind<ClassTest>().ToConstructor(x => new ClassTest(x.Inject<InterfaceA>())).Named("A");
Bind<ClassTest>().ToConstructor(x => new ClassTest(x.Inject<Func<ClassB>>())).Named("B");
kernel.Get<ClassTest>("A");
kernel.Get<ClassTest>("B");

How to instantiate the repository that uses ninject in a unit test

I have a repository like:
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class, IEntity
{
private readonly IContext _db;
public Repository(IContext context)
{
_db =context;
}
...
In Global.asax I have setup the ninject as:
kernel.Bind<IContext>().To<Context>();
This is working fine in the app probably because I'm explicity instantiating by calling the constructor with a paramater. There are problems in the unit tests however.
Then in a unit test I have:
var mockUnitOfWork = new Mock<UnitOfWork>();
var mockProjectApprovalRepository = new Mock<Repository<ProjectApproval>>();
mockUnitOfWork.Setup(x => x.ProjectApprovalRepository).Returns(mockProjectApprovalRepository.Object);
On this last line I get the error:
Can not instantiate proxy of class: MyNamespace.Repository Could not find a parameterless constructor.
I'm confused by this because I thought the point of Ninject was I didn't need to specify a parameterless constructor. Shouldn't ninject have instantiated a Context and used the constructor with one parameter.
When you do new Mock<Repository<ProjectApproval>>(), you're asking Moq to construct the object. If you asked Ninject to construct it, it would do it.
Ninject doesn't magically step in wherever construction happens - new is still new.
In this case, you can use an overload of the Mock constructor wherein you specify extra args.
Note that its generally accepted that Ninject shouldnt be anywhere near anything remotely close to the any common definition of the term Unit Test.

Resources