Ignacio Soler Garcia
Ignacio Soler Garcia

Reputation: 21855

How to do proper IoC in this situation?

I have the following class implementing a 3rd party interface:

public class RegistrationService : IRegistrationService
{
    public void Register()
    {
        ....
    }
}

As this class is responsible of some parts of application initialization I don't have some required class dependencies available at construct time so I cannot pass them in the constructor like you normally do following IoC.

I cannot modify the Register method as this would imply changing the interface which is a 3rd party.

If I create the dependencies I need on the Register method like:

{
    IRequiredService requiredService;

    public void Register()
    {
        this.requiredService = new RequiredService();
    }
}

Then I cannot mock the RequiredService to UnitTest the class. I'm using Unity and I have the container available in the class but I don't see how it can help me.

Any help will be really appreciated.

Upvotes: 0

Views: 60

Answers (2)

Neil
Neil

Reputation: 2688

Could you use property injection instead?

public class RegistrationService : IRegistrationService
{
    [Dependency]
    public IRequiredService RequiredService { get; set; };

    public void Register()
    {}
}

Think I prefer Matthew's approach though!

Cheers

Upvotes: 1

Matthew Watson
Matthew Watson

Reputation: 109567

You could pass into the constructor a factory delegate that you can use to create a RequiredService when required.

Something like:

private readonly Func<IRequiredService> serviceCreator;

public RegistrationService(Func<IRequiredService> serviceCreator)
{
    this.serviceCreator = serviceCreator;
    ...

Then in Register():

public void Register()
{
    this.requiredService = serviceCreator();
}

Upvotes: 4

Related Questions