Lijin Durairaj
Lijin Durairaj

Reputation: 3501

How to implement DI using Unity on a class which has a constructor - mvc?

suppose i have a interface and class like this

public interface ILienholderBusinessService
    {
        string GetCoverage(IList<PolicyVinRequest> InputList);
    }

public class LienholderBusinessService : ILienholderBusinessService
    {
        public ILienholderPolicySearchDataService LienholderPolicySearchDataService { get; set; }

        public LienholderBusinessService(ILienholderPolicySearchDataService  LienholderPolicySearchDataService )
        {
            this.LienholderPolicySearchDataService =LienholderPolicySearchDataService ;
        }
        public string GetCoverage(IList<PolicyVinRequest> InputList)
        {
            return "my string";

        }
    }

I have a controller like this

 public class InsuranceVerificationPortalController : Controller
    {
        public ILienholderBusinessService LienholderBusinessService { get; set; }
        public InsuranceVerificationPortalController(ILienholderBusinessService LienholderBusinessService)
        {
            this.LienholderBusinessService = LienholderBusinessService;
        }
}

now when i try to implement unity in my MVC, i get error like

are you missing any type

How can i implement DI using Unity on a class which has a constructor

Upvotes: 0

Views: 44

Answers (1)

Randy Levy
Randy Levy

Reputation: 22655

You'll have to register mappings for all interfaces that you need to resolve concrete types for. From the posted code this would be ILienholderBusinessService and ILienholderPolicySearchDataService:

container.RegisterType<ILienholderBusinessService, LienholderBusinessService>();
container.RegisterType<ILienholderPolicySearchDataService, LienholderPolicySearchDataService>();

It could be that the implementation of ILienholderPolicySearchDataService also depends on interfaces/abstract classes (e.g. IRepository<T>). If that is the case then mappings will need to be created for those as well.

By default, Unity will select the constructor with the most number of parameters so if you need to choose another constructor you can use an InjectionConstructor. e.g.

container.RegisterType<ILienholderPolicySearchDataService, LienholderPolicySearchDataService>(
    new InjectionConstructor(typeof(IRepository<Policy>)));

Upvotes: 1

Related Questions