Singularity303
Singularity303

Reputation: 69

How to resolve Action parameter with Autofac

How to execute resolve parameter, if it Action type?

public class TaskWrapper : ITaskWrapper
{
    public TaskWrapper(Action action)
    {
        this.action = action;
    }
}

public void Connect()
{
    Program.Container.Resolve<TaskWrapper>(new NamedParameter("action", ToConnect)); // not work!
    Program.Container.Resolve<TaskWrapper>(new TypedParameter(typeof(Action), ToConnect)); // not work!
}

private void ToConnect()
{
    // some code...
}

NamedParameter and TypedParameter don't work

Upvotes: 2

Views: 504

Answers (1)

tdragon
tdragon

Reputation: 3329

First of all, you are not supposed to expose container, as you do with your Program.Container property, and resolve your dependencies. It's a classic example of Service Locator, and it is considered an anti-pattern. But if you really need or want to do that, your code should look like this:

public void Connect()
{
    Action action = Connect;
    Program.Container.Resolve<ITaskWrapper>(new NamedParameter("action", action));
}

Much better approach would be to use dependency injection how it really should be used - to inject dependencies.

public class Connector : IConnector
{
    public Connector(Func<Action, ITaskWrapper> taskWrapperFactory)
    {
        var taskWrapper = taskWrapperFactory(Connect);
    }

    private void Connect()
    {            
    }
}

public class TaskWrapper : ITaskWrapper
{
    private readonly Action _task;

    public TaskWrapper(Action task)
    {
        _task = task;
    }
}

You could move your connection-related methods to some class, like Connector, and inject your TaskWrapper in constructor. Using Func<> allows you to create instances and pass non-resolvable parameters.

Also, you should resolve/inject your dependencies using proper interfaces, not types directly, as you loose the whole idea of loosely-coupled components completely.

Upvotes: 2

Related Questions