0
votes

I have MVC5 application and i am using Unity as IOC container. I am registering all the components as shown below. Everything was working fine until i introduced new class MyAccount into MyDomainService.

Now when unity try to resolve HomeController -> MyDomainService -> MyAccount i get error

Value cannot be null. Parameter name: String

well MyAccount constructor does not have any parameter

    public class MyAccount
    {
        public MyAccount()
        {

        }       
    }

    public class MyDomainService:IDisposable
    {       
        private IGenericRepository _repository;
        private MyAccount _myAccount;

        // it works if i remove MyAccount from the constructor
        public MyDomainService(IGenericRepository repository, MyAccount MyAccount)
        {
            _repository = repository;
            _myAccount = MyAccount;
        }
    }


    public static class UnityConfig
    {
        public static void RegisterComponents()
        {
            var container = new UnityContainer();

            container.RegisterType<MyDomainService, MyDomainService>(new HierarchicalLifetimeManager());
            container.RegisterType<IGenericRepository, GenericRepository>(new HierarchicalLifetimeManager());
            container.RegisterType<DbContext, MYDbContext>(new HierarchicalLifetimeManager());            
            container.RegisterType<MyAccount, MyAccount>();

            // MVC5
            DependencyResolver.SetResolver(new Unity.Mvc5.UnityDependencyResolver(container));       
            UnityServiceLocator locator = new UnityServiceLocator(container);
            ServiceLocator.SetLocatorProvider(() => locator);
        }
    }


    public class HomeController:Controller
    {
        MyDomainService _service;
        public HomeController(MyDomainService service)
        {
            _service = service;
        }
    }
1

1 Answers

0
votes

This is not how Unity DependencyInjection works out of the box.

You should always accept only DependencyInjection entities to the constructor, and only if the entire class (e.g MyDomainService) can not live without any of the passes dependencies.

If DomainService is:

  • Strongly depended in both IGenericRepository and MyAccount then you should consider making MyAccount also registered at the IOC container(and redesign the class accordingly).

  • Strongly depended only in IGenericRepository or MyAccount(after redesign) then you should pass the constructor only the one that is depended and pass the methods the used depended entities.

For example

public DomainService(IGenericRepository genericRepository) { ... }

public void Method1(MyAccount account) { .. }
public void AnotherExampleMethod2(AnotherDependedClass anotherClass, int justANumber) { .. }