2

I would like to use property injection in an MVC3 application. I have configured Unity 2 as a DI container and everything works just fine by constructor injection but I can't figure out how to use property injection. I marked properties with the [Dependency] attribute but it doesn't work.

public class UnityDependencyResolver : IDependencyResolver
{
    IUnityContainer _container;


    public UnityDependencyResolver(IUnityContainer container)
    {
        _container = container;
    }


    public object GetService(Type serviceType)
    {
        try
        {
            return _container.Resolve(serviceType);
        }
        catch (Exception)
        {
            return null;
        }
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {
            return _container.ResolveAll(serviceType);
        }
        catch (Exception)
        {
            return new List<object>();
        }
    }
}

In Global.asax I have the following:

var container = new UnityContainer(); 

        var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
        section.Configure(container);

        DependencyResolver.SetResolver(new UnityDependencyResolver(container));

Any help is appreciated.

Zoliqa
  • 1,015
  • 2
  • 15
  • 36
  • Why do you want to use Property Injection? In general, it's far inferior to Constructor Injection. – Mark Seemann Oct 03 '11 at 14:30
  • I would like to use because I have a lot of parameters and I have extended classes too and I have to write a lot of tedious code to manage things. – Zoliqa Oct 03 '11 at 14:51
  • 1
    Property Injection isn't going to solve that problem - it's just going to make it even worse. Lots of dependencies is a symptom of another problem: http://stackoverflow.com/questions/2420193/dependency-injection-constructor-madness/2420245#2420245 – Mark Seemann Oct 03 '11 at 18:08
  • 4
    The question was how to use property injection, I didn't ask for arguments for or against it. That's another story that has nothing to do with the question. – Zoliqa Oct 04 '11 at 06:36

0 Answers0