Unity not resolving dependencies in MVC3 controller's constructor - asp.net-mvc

We have an MVC3 controller in which there is some 'common' work that we rolled into the controller constructor. Some of that common work is done by a losely coupled class (say ourService) that's dynamically resolved through Unity (for IoC / Dependency injection). ourService is null (i.e. not resolved) in the Controller's constructor BUT it's properly resolved in the usual Controller methods. The simple demo code below shows the issue:
public class Testing123Controller : BaseController
{
[Dependency]
public IOurService ourService { get; set; }
public Testing123Controller()
{
ourService.SomeWork(1); // ourService=null here !!
...
}
public ActionResult Index()
{
ourService.SomeWork(1); // resolved properly here here !!
...
}
...
}
Question:
Why is there this different in Unity resolution behavior? I would expect consistent behavior.
How can I fix it so Unity resolves this even in the controller's contructor?
The way we've setup Unity 2.0 is :
Global.asax
Application_Start()
{
...
Container = new UnityContainer();
UnityBootstrapper.ConfigureContainer(Container);
DependencyResolver.SetResolver(new UnityDependencyResolver(Container));
...
}
public static void ConfigureContainer(UnityContainer container)
{
...
container.RegisterType<IOurService, OurService>();
...
}
IOurService.cs
public interface IOurService
{
bool SomeWork(int anInt);
}
OurService.cs
public class OurService: IOurService
{
public bool SomeWork(int anInt)
{
return ++anInt; //Whew! Time for a break ...
}
}

As a basic principle of classes, before an instance property can be set, the instance has to be instantiated.
Unity needs to set the dependency property, but it can't do so until the instance has been fully instantiated - i.e. the constructor must have completed executing.
If you are referencing the dependency property in the constructor, then this is too early - there is no way for Unity to have set it yet - and therefore it will be unset (i.e. null).
If you need to use the dependency in the constructor, then you must use constructor injection. Although in general, using constructor injection is usually the better method anyway:
public class Testing123Controller : BaseController
{
public IOurService ourService { get; set; }
public Testing123Controller(IOurService ourService)
{
this.ourService = ourService;
this.ourService.SomeWork(1); // ourService no longer null here
...
}
public ActionResult Index()
{
ourService.SomeWork(1); // also resolved properly here
...
}
...
}
Note: In the example I left ourService as a publicly gettable & settable property in case other parts of your code need to access it. If on the other hand it is only accessed within the class (and had only been made public for Unity purposes), then with the introduction of constructor injection, it would be best to make it a private readonly field.

You are using property injection (by using the Dependency attribute) rather than constructor injection so the dependency is not resolved until after the controller is instantiated. If you want to have access to the dependency is the constructor, just add it to the ctor:
private readonly IOurService _ourService { get; set; }
public Testing123Controller(IOurService ourService)
{
_ourService = ourService;
_ourService.SomeWork(1); // ourService=null here !!
...
}

I'm afraid that for Unity to work on the constructor, the instance itself must be resolved using Unity. The fact that the Service property is null in the constructor supports this idea. If you call the Controller yourself (NOT with Unity), Unity has no time to resolve the property.

Related

How to Inject properly an IDBContextFactory into a controller's inject IDomainFactory using Ninject MVC3?

Preliminaries
I'm using Ninject.MVC3 2.2.2.0 Nuget Package for injecting into my controller an implementation of a IDomain Interface that separates my Business Logic (BL) using an Factory approach.
I'm registering my Ninject Modules in the preconfigured NinjectMVC3.cs using:
private static void RegisterServices(IKernel kernel)
{
var modules = new INinjectModule[]
{
new DomainBLModule(),
new ADOModule()
};
kernel.Load(modules);
}
I'm trying to avoid the fatal curse of the diabolic Service Locator anti-pattern.
The Domain Class uses a DBContext that i'm trying to inject an interface implementation too, via an IDBContext, with the following scenario:
IDomainBLFactory:
public interface IDomainBLFactory
{
DomainBL CreateNew();
}
DomainBLFactory:
public class DomainBLFactory : IDomainBLFactory
{
public DomainBL CreateNew()
{
return new DomainBL();
}
}
In the controller's namespace:
public class DomainBLModule : NinjectModule
{
public override void Load()
{
Bind<IDomainBLFactory>().To<DomainBLFactory>().InRequestScope();
}
}
At this point i can inject the IDomainBLFactory implementation into my controller using Ninject Constructor Injection without any problem:
public class MyController : Controller
{
private readonly IDomainBLFactory DomainBLFactory;
// Default Injected Constructor
public MyController(IDomainBLFactory DomainBLFactory)
{
this.DomainBLFactory = DomainBLFactory;
}
... (use the Domain for performing tasks/commands with the Database Context)
}
Now my central problem.
In the DomainBL implementation, i will inject the dependency to a particular DBContext, in this case ADO DBContext from Entity Framework, again, using a IDBContextFactory:
IDbDataContextFactory
public interface IDbDataContextFactory
{
myADOEntities CreateNew();
}
DbDataContextFactory
public class DbDataContextFactory : IDbDataContextFactory
{
public myADOEntities CreateNew()
{
return new myADOEntities ();
}
}
ADOModule
public class ADOModule : NinjectModule
{
public override void Load()
{
Bind<IDbDataContextFactory>().To<DbDataContextFactory>().InRequestScope();
}
}
Now in the DomainBL implementation I faced the problem of injecting the necessary interface for the DBContext Object Factory:
public class DomainBL
{
private readonly IDbDataContextFactory contextFactory;
**** OPS, i tried to understand about 10+ Stackoverflow articles ***
...
}
What have I tried?
To Use the constructor Injection. But I don't know what to inject in the call for the Factory CreateNew() in the IDBContextFactory. For clear:
public class DomainBLFactory: IDomainBLFactory
{
// Here the constructor requires one argument for passing the factory impl.
public DomainBL CreateNew()
{
return new DomainBL(?????) // I need a IDBContextFactory impl to resolve.
//It's not like in the MVC Controller where injection takes place internally
//for the controller constructor. I'm outside a controller
}
}
In this Useful Post, our unique true friend Remo Gloor describes in a comment a possible solution for me, citing: "Create an interface that has a CreateSomething method that takes everything you need to create the instance and have it return the instance. Then in your configuration you implement this interface and add an IResolutionRoot to its constructor and use this instace to Get the required object."
Questions: How do I implement this in a proper way using Ninject.MVC3 and my modest Domain Class approach? How do I Resolve the IResolutionRoot without be punished for relaying in the Service Locator anti-pattern?
To Use the property injection for an IDBContexFactory. In the course of learning and reading all the contradictory points of view plus the theoretical explanations about it, I can deduce it's not a proper way of doing the injection for my DBContexFactory class code. Nevermind. It doesn't work anyway.
public class DomainBL
{
[Inject]
public IDbDataContextFactory contextFactory
{
get;
set;
}
//Doesn't works, contextFactory is null with or without parameterless constructor
.... (methods that uses contextFactory.CreateNew()....
}
Question: What am I missing? Even if this approach is wrong the property is not injecting.
Be cursed. Use a DependencyResolver and live with the stigmata. This works and I will remain in this approach until a proper solution appears for me. And this is really frustrating because the lack of knowledge in my last 10 days effort trying to understand and do things right.
public class DomainBL
{
private readonly IDbDataContextFactory contextFactory;
this.contextFactory = DependencyResolver.Current.GetService<IDbDataContextFactory>();
//So sweet, it works.. but i'm a sinner.
}
Question: Is there a big mistake in my understanding of the Factory Approach for the injection of interfaced implementations and using a Domain Driven Approach for taking apart the Business Logic? In the case I'm wrong, what stack of patterns should I implement with confidence?
I saw before a really big quantity of articles and blogs that does not ask this important question in a open a clear way.
Remo Gloor introduces the Ninject.Extensions.Factory for the Ninject 3.0.0 RC in www.planetgeek.ch/2011/12/31/ninject-extensions-factory-introduction.
Question: Will this extension work coupled with Ninject.MVC3 for general porpouse?. In such case it should be my hope for the near future.
Thank you all in advance for your guidance and remember we appreciate your kind help. I think a lot of people will find this scenario useful too.
I don't really get the purpose of your factories. Normally, you have exactly one ObjectContext instance for one request. This means you don't need the factory and can simply bind myADOEntities in Request scope and inject it into your DomainBL without adding the factories:
Bind<myADOEntities>().ToSelf().InRequestScope();
Bind<DomainBL>().ToSelf().InRequestScope();
And Yes the factory and mvc extrensions work together.
Here's an implementation of a generic IFactory to solve the problem without resorting to the ServiceLocator anti-pattern.
First you define a nice generic factory interface
public interface IFactory<T>
{
T CreateNew();
}
And define the implementation which uses ninject kernel to create the objects requested
class NinjectFactory<T> : IFactory<T>
{
private IKernel Kernel;
public NinjectFactory( IKernel Kernel )
{
this.Kernel = Kernel;
}
public T CreateNew()
{
return Kernel.Get<T>();
}
}
Binding to your factory using the following
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<myADOEntities>().ToSelf();
kernel.Bind<DomainBL>().ToSelf();
kernel.Bind(typeof(IFactory<>)).To(typeof(NinjectFactory<>));
}
You can now do the following in your controller.
public class MyController : Controller
{
private readonly IFactory<DomainBL> DomainBLFactory;
public MyController( IFactory<DomainBL> DomainBLFactory )
{
this.DomainBLFactory = DomainBLFactory;
}
// ... (use the Domain for performing tasks/commands with the Database Context)
}
And in your DomainBL
public class DomainBL
{
IFactory<myADOEntities> EntitiesFactory;
public DomainBL( IFactory<myADOEntities> EntitiesFactory )
{
this.EntitiesFactory = EntitiesFactory;
}
// ... (use the Entities factory whenever you need to create a Domain Context)
}

System.NotSupportedException: Parent does not have a default constructor. The default constructor must be explicitly defined

I'm working with Ninject 2.0.2
Ninject.Extensions.Interception
with DynamicProxy2
Castle.Core
Castle.DynamicProxy2
The injection worked fine.
Then I inserted the wcf between controller and bl layers.
For interaction between the layers I've used the
Ninject.Extensions.Interception of Ian Davis.
I've used the DynamicProxy2 for creating proxies with help of
Castle.Core and Castle.DynamicProxy2.
In my Bl layer in classes there are references to implementation Types
in DAL Layer.
The interceptor is working when I'm marking the attribute of [Inject]
on any property existed in BL layer .
It means that when I cut off my connections from BL to DAL it works
but it's useless .
So the question is how to preserve the option of addressing DAL even
though I'm doing it through intercept method.
I've found only post that refers to the subject -
http://dotnet.dzone.com/news/ninject-2-dependency-injection?utm_sourc...)
but it doesn't explain how to deal with it.
In every class I've already created a constructor and also put an
[Inject] attribute above it.
Note:
If I remove Inject from property of IMyClassDao , I'm getting the
Injection but without the property - it stays dead.
How can I revive it ?
I've upgraded recently to Ninject 2.0.2 from 1.5 - can it related
version issue ?
Does anyone has a solution for it?
Kernel handling :
using Ninject;
using Ninject.Modules;
using System.Configuration;
using System;
using Ninject.Extensions.Interception;
using Ninject.Extensions.Interception.Infrastructure.Language;
using Ninject.Extensions.Interception.Request;
private static IKernel createDefault()
{
IKernel _kernel = new StandardKernel(new
ControllerToBLModule(),new NHibernateModule(), new BlToDalModule());
_kernel.Intercept(doIntercept).With<ControllerToBlInterceptor>();
return _kernel;
}
in controller to bl:
public class ControllerToBLModule : NinjectModule
{
public override void Load()
{
Bind<IMyInterfaceBL>().To<MyClassBL>().InRequestScope();
}
}
in bl to dal :
public class BlToDalModule : NinjectModule
{
public override void Load()
{
Bind<IMyClassDao>().To<MyClassDaoImpl>().InRequestScope();
}
}
So the code in my Bl is something like this
public class MyClassBL: GlobalBL , IMyInterfaceBL
{
[Inject]
public MyClassBL() : base() { }
[Inject]
public IMyClassDao _daoInstance{get;set;}
public virtual IList<MyObject> GetMyObject()
{
...
}
}
and in DAL :
public class MyClassDaoImpl : GlobalDAOImpl, IMyClassDao
{
[Inject]
public MyClassDaoImpl() : base() { }
public virtual IList<MyObject> GetMyObjectDao()
{
...
}
}
the error I'm getting :
Execute
System.NotSupportedException: Parent does not have a default constructor. The default constructor must be explicitly defined.
at System.Reflection.Emit.TypeBuilder.DefineDefaultConstructorNoLock(MethodAtt ributes
attributes)
at System.Reflection.Emit.TypeBuilder.DefineDefaultConstructor(MethodAttribute s
attributes)
at System.Reflection.Emit.TypeBuilder.CreateTypeNoLock()
at System.Reflection.Emit.TypeBuilder.CreateType()
at Castle.DynamicProxy.Generators.Emitters.AbstractTypeEmitter.CreateType(Type Builder
type) in e:\horn.horn\ioc\castle.dynamicproxy\Working-2.2\src ....
Does anyone have any idea on how I can preserve the hierarchy of addressing the layers through Ninject during using the intercept method ?

How do I handle classes with static methods with Ninject?

How do I handle classes with static methods with Ninject?
That is, in C# one can not have static methods in an interface, and Ninject works on the basis of using interfaces?
My use case is a class that I would like it to have a static method to create an
unpopulated instance of itself.
EDIT 1
Just to add an example in the TopologyImp class, in the GetRootNodes() method, how would I create some iNode classes to return? Would I construct these with normal code practice or would I somehow use Ninject? But if I use the container to create then haven't I given this library knowledge of the IOC then?
public interface ITopology
{
List<INode> GetRootNodes();
}
public class TopologyImp : ITopology
{
public List<INode> GetRootNodes()
{
List<INode> result = new List<INode>();
// Need code here to create some instances, but how to without knowledge of the container?
// e.g. want to create a few INode instances and add them to the list and then return the list
}
}
public interface INode
{
// Parameters
long Id { get; set; }
string Name { get; set; }
}
class NodeImp : INode
{
public long Id
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public string Name
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
}
// Just background to highlight the fact I'm using Ninject fine to inject ITopology
public partial class Form1 : Form
{
private ITopology _top;
public Form1()
{
IKernel kernal = new StandardKernel(new TopologyModule());
_top = kernal.Get<ITopology>();
InitializeComponent();
}
}
If you're building a singleton or something of that nature and trying to inject dependencies, typically you instead write your code as a normal class, without trying to put in lots of (probably incorrect) code managing the singleton and instead register the object InSingletonScope (v2 - you didnt mention your Ninject version). Each time you do that, you have one less class that doesnt surface its dependencies.
If you're feeling especially bloody-minded and are certain that you want to go against that general flow, the main tools Ninject gives you is Kernel.Inject, which one can use after you (or someone else) has newd up an instance to inject the dependencies. But then to locate one's Kernelm you're typically going to be using a Service Locator, which is likely to cause as much of a mess as it is likely to solve.
EDIT: Thanks for following up - I see what you're after. Here's a hacky way to approximate the autofac automatic factory mechanism :-
/// <summary>
/// Ugly example of a not-very-automatic factory in Ninject
/// </summary>
class AutomaticFactoriesInNinject
{
class Node
{
}
class NodeFactory
{
public NodeFactory( Func<Node> createNode )
{
_createNode = createNode;
}
Func<Node> _createNode;
public Node GenerateTree()
{
return _createNode();
}
}
internal class Module : NinjectModule
{
public override void Load()
{
Bind<Func<Node>>().ToMethod( context => () => Kernel.Get<Node>() );
}
}
[Fact]
public void CanGenerate()
{
var kernel = new StandardKernel( new Module() );
var result = kernel.Get<NodeFactory>().GenerateTree();
Assert.IsType<Node>( result );
}
}
The ToMethod stuff is a specific application of the ToProvider pattern -- here's how you'd do the same thing via that route:-
...
class NodeProvider : IProvider
{
public Type Type
{
get { return typeof(Node); }
}
public object Create( IContext context )
{
return context.Kernel.Get<Node>();
}
}
internal class Module : NinjectModule
{
public override void Load()
{
Bind<Func<Node>>().ToProvider<NodeProvider>();
}
}
...
I have not thought this through though and am not recommending this as A Good Idea - there may be far better ways of structuring something like this. #Mark Seemann? :P
I believe Unity and MEF also support things in this direction (keywords: automatic factory, Func)
EDIT 2: Shorter syntax if you're willing to use container-specific attributes and drop to property injection (even if Ninject allows you to override the specific attributes, I much prefer constructor injection):
class NodeFactory
{
[Inject]
public Func<Node> NodeFactory { private get; set; }
public Node GenerateTree()
{
return NodeFactory();
}
}
EDIT 3: You also need to be aware of this Ninject Module by #Remo Gloor which is slated to be in the 2.4 release
EDIT 4: Also overlapping, but not directly relevant is the fact that in Ninject, you can request an IKernel in your ctor/properties and have that injected (but that doesn't work directly in a static method).

How to pass controller's ModelState to my service constructor with Autofac?

I have a wrapper on ModelStateDictionary which all my services accept. Is it possible to configure the autofac to inject the controller ModelStateDictionary into the constructor of the wrapper and then inject it into service constructor?
//code
public class ModelValidation : IModelValidation {
public ModelValidation(ModelStateDictionary msd){...}
..
..
}
public class CustomerService{
public CustomerService(IModelValidation mv){...}
..
}
Thanks
Based on your comments I hereby revise my answer :)
ModelStateDictionary is clearly not a service that should be resolved by the container, but rather data that should be provided at instantiation time. We can tell that from the fact that ModelState is owned by each Controller instance and is thus not available to the container at "resolve time".
Furthermore, each ModelValidation instance will be bound to a ModelStateDictionary instance and is thus also to be considered as data.
In Autofac, when data must be passed to constructors (optionally in addition to other dependencies), we must use factory delegates. These delegates will handle dependency and data passing to the constructor. The sweet thing with Autofac is that these delegates can be autogenerated.
I propose the following solution:
Since both ModelValidation and CustomerService requires data in their constructors, we need two factory delegates (note: the parameter names must match the names in their corresponding constructor):
public delegate IModelValidation ModelValidationFactory(ModelStateDictionary msd);
public delegate CustomerService CustomerServiceFactory(ModelStateDictionary msd);
Since your controllers shouldn't know where these delegates comes from they should be passed to the controller constructor as dependencies:
public class EditCustomerController : Controller
{
private readonly CustomerService _customerService;
public EditCustomerController(CustomerServiceFactory customerServiceFactory
/*, ...any other dependencies required by the controller */
)
{
_customerService = customerServiceFactory(this.ModelState);
}
}
The CustomerService should have a constructor similar to this (optionally handle some of this in a ServiceBase class):
public class CustomerService
{
private readonly IModelValidation _modelValidation;
public CustomerService(ModelStateDictionary msd,
ModelValidationFactory modelValidationFactory)
{
_modelValidation = modelValidationFactory(msd);
}
To make this happen we need to build our container like this:
var builder = new ContainerBuilder();
builder.Register<ModelValidation>().As<IModelValidation>().FactoryScoped();
builder.Register<CustomerService>().FactoryScoped();
builder.RegisterGeneratedFactory<ModelValidationFactory>();
builder.RegisterGeneratedFactory<CustomerServiceFactory>();
builder.Register<EditCustomerController>().FactoryScoped();
So, when the controller is resolved (eg when using the MvcIntegration module), the factory delegates will be injected into the controllers and services.
Update: to cut down on required code even more, you could replace CustomerServiceFactory with a generic factory delegate like I've described here.
Builder.RegisterInstance(new ModelStateDictionary()).SingleInstance();
builder.Register(c => new SW.PL.Util.ModelStateWrapper
(c.Resolve<ModelStateDictionary>())).As<IValidationDictionary>().InstancePerHttpRequest();
Add a new constructor without ValidationService. Assign the ValidationService by using a property.
The property must be implemented in the interface ICostumerService
public class ModelStateWrapper: IValidationDictionary {
public ModelStateWrapper(ModelStateDictionary msd){}
}
public class CustomerService: ICostumerService{
public IValidationDictionary ValidationDictionary { get; set; }
public CustomerService(ICustomerRepsitory customerRepository, IValidationDictionary validationDictionary ){}
public CustomerService(ICustomerRepsitory customerRepository){}
}
public Controller(ICustomerService customerService)
{
_customerService= menuService;
_customerService.ValidationDictionary = new ModelStateWrapper(this.ModelState);
_customerService= sportsService;
}

How do I use Windsor to inject dependencies into ActionFilterAttributes

Having seen how NInject can do it and AutoFac can do it I'm trying to figure out how to inject dependencies into MVC ActionFilters using Castle Windsor
At the moment I'm using an ugly static IoC helper class to resolve dependencies from the constructor code like this:
public class MyFilterAttribute : ActionFilterAttribute
{
private readonly IUserRepository _userRepository;
public MyFilterAttribute() : this(IoC.Resolve<IUserRepository>()) { }
public MyFilterAttribute(IUserRepository userRepository)
{
_userRepository = userRepository;
}
}
I'd love to remove that static antipattern IoC thing from my filters.
Any hints to as how I would go about doing that with Castle Windsor?
And no, changing DI framework is not an option.
When I needed this, I built upon the work others have done with Ninject and Windsor to get property injection dependencies on my ActionFilters.
Make a generic attribute: MyFilterAttribute with ctor taking a Type as argument - i.e. something like this:
public class MyFilterAttribute : ActionFilterAttribute {
public MyFilterAttribute(Type serviceType) {
this.serviceType = serviceType;
}
public override void OnActionExecuting(FilterExecutingContext c) {
Container.Resolve<IFilterService>(serviceType).OnActionExecuting(c);
// alternatively swap c with some context defined by you
}
// (...) action executed implemented analogously
public Type ServiceType { get { return serviceType; } }
public IWindsorContainer Container { set; get; }
}
Then use the same approach as the two articles you are referring to, in order to take control of how actions are invoked, and do a manual injection of your WindsorContainer into the attribute.
Usage:
[MyFilter(typeof(IMyFilterService))]
Your actual filter will then be in a class implementing IMyFilterService which in turn should implement IFilterService which could look something like this:
public interface IFilterService {
void ActionExecuting(ActionExecutingContext c);
void ActionExecuted(ActionExecutedContext c);
}
This way your filter will not even be tied to ASP.NET MVC, and your attribute is merely a piece of metadata - the way it is actually supposed to be! :-)

Resources