LP13
LP13

Reputation: 34109

Unity throws error 'Value cannot be null. Parameter name: String'

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 a new class MyAccount into MyDomainService.

Now when Unity tries to resolve HomeController -> MyDomainService -> MyAccount, I get an error:

Value cannot be null. Parameter name: String

Well, MyAccount's 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;
    }
}

Upvotes: 0

Views: 1273

Answers (1)

Orel Eraki
Orel Eraki

Reputation: 12196

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) { .. }

Upvotes: 0

Related Questions