0

Just wondering if anyone had this scenario with Unity(as an IoC container) where the class has two injected dependencies(interfaces) where one dependency can be null. For example:

public MyServiceDll(IRepository repository, ICanBeNullDependency canBeNullDependency = null)
{
    _repository = repository;
    _canBeNullDependency = canBeNullDependency;
}

ICanBeNullDependency is from another assembly. MyServiceDll is another assembly. MyServiceDll is referenced by web api and injected its interface in one of the controllers. ICanBeNullDependency can be null so I don't need to register an implementation of this interface in unityconfig.cs but when the controller gets called it will error saying:

The current type, ICanBeNullDependency, is an interface and cannot be constructed. Are you missing a type mapping?

1 Answer 1

3

For dependencies that are not always required, you can use the null object pattern.

public interface ICanBeNullDependency
{
    void DoSomething();
}

public class AcutallyDoSomething : ICanBeNullDependency
{
    public void DoSomething()
    {
         Console.WriteLine("something done");
    }
}

public class NullDoSomething : ICanBeNullDependency
{
    public void DoSomething()
    {
        // Do nothing - this class represents a null
    }
}

Then if you want a "null state", you inject an instance of the null class.

The main advantage over actually making the variable null is that you don't need any conditional logic in your service to deal with a null, and of course it is DI-friendly.

Sign up to request clarification or add additional context in comments.

1 Comment

I would even say "you should use the null object pattern."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.