0

i use Unity DI in project, but when redirect from one action to another get this error: No parameterless constructor defined for this object. in FirstController _service property is initialized correct, and when call SecondController directly _service property is initialized correct, but when use RedirctToAction method from FirstController to redirect to SecondController get this Error:No parameterless constructor defined for this object. my sample code is:

public interface IService
{
    string Get();
}

public class Service : IService
{
    public string Get()
    {
        return "Data";
    }
}
public class FirstController : Controller
{
    private readonly IService _service;

    public FirstController(IService service)
    {
        _service = service;
    }

    public ActionResult Index()
    {
        return RedirectToAction("Index", "Second"); -----> this line
    }
}

public class SecondController : Controller
{
    private readonly IService _service;

    public SecondController(IService service)
    {
        _service = service;
    }

    public ActionResult Index()
    {
        return View();
    }
}

DI Code:

public static class Bootstrapper
{
    public static IUnityContainer Initialise()
    {
        var container = BuildUnityContainer();

        System.Web.Mvc.DependencyResolver.SetResolver(new DependencyResolver(container));

        return container;
    }

    private static IUnityContainer BuildUnityContainer()
    {
        var container = new UnityContainer();

        container.RegisterType<IService, Service>();

        return container;
    }
}

public class DependencyResolver : IDependencyResolver
{
    private readonly IUnityContainer _unityContainer;

    public DependencyResolver(IUnityContainer unityContainer)
    {
        _unityContainer = unityContainer;

    }
    public object GetService(System.Type serviceType)
    {
        try
        {
            var service = _unityContainer.Resolve(serviceType);

            return service;
        }
        catch (Exception ex)
        {
            return null;
        }
    }

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

Application_Start Initialise:

Bootstrapper.Initialise();
Mohammad Akbari
  • 4,486
  • 6
  • 43
  • 74

0 Answers0