MVC 3 beta + Dependency Resolver + Unity = got problem

Posted by drsim on Stack Overflow See other posts from Stack Overflow or by drsim
Published on 2010-11-27T22:31:05Z Indexed on 2011/01/14 20:53 UTC
Read the original article Hit count: 145

Hi everyone. I'm tried to use Dependency Resolver with Unity, and got some problem when my Controller creating. Here example of controller:

public class AccountController : Controller
{
    private readonly ICourseService _courseService;

    public AccountController(ICourseService courseService)
    {
         _courseService = courseService;
    }
}

But, when Controller try to create - i got an exception "No parameterless constructor defined for this object." I even try to add default constructor for this controller, but courseService didn't create. Also try to add property with [Dependency] attribute - nothing happened. Here is Dependency Resolver class:

public class UnityDependencyResolver : IDependencyResolver
{
    private readonly IUnityContainer _container;
    public UnityDependencyResolver(IUnityContainer container)
    {
        _container = container;
    }

    public object GetService(Type serviceType)
    {
        return _container.IsRegistered(serviceType) ? _container.Resolve(serviceType) : null;
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        return _container.IsRegistered(serviceType) ? _container.ResolveAll(serviceType) : new List<object>();
    }
}

and Global.asax.cs:

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);

        var container = new UnityContainer();
        container.RegisterType<ICourseService, CourseService>();

        DependencyResolver.SetResolver(new UnityDependencyResolver(container));
    }

Can anyone help me ?

© Stack Overflow or respective owner

Related posts about c#

Related posts about dependency-injection