Based on the article here, how does one go about creating instances that take dependencies via constructor?

E.g.

var container = new Container();

var factory = new RequestHandlerFactory(container);

factory.Register<DefaultRequestHandler>("default");
factory.Register<OrdersRequestHandler>("orders");
factory.Register<CustomersRequestHandler>("customers");

container.RegisterSingle<IRequestHandlerFactory>(factory);

Now if I were to create OrdersRequestHandler using some constructor injected dependencies like this:

public OrdersRequestHandler(string uri, IOrderValidationService) {
    // do something with deps
}

how would that be done?

I've tried registering the implementation with constructor arguments and then registering with the factory, but that results in an error as the factory is unable to create the instance.

有帮助吗?

解决方案

You can do that by adding the following method to the RequestHandlerFactory:

public void Register(string name, Func<IRequestHandler> factory) {

    var producer = Lifestyle.Transient
        .CreateProducer<IRequestHandler>(factory, container);

    this.producers.Add(name, producer);
}

You can use it as follows:

factory.Register("orders", () => new OrdersRequestHandler(
    "my uri",
    container.GetInstance<IOrderValidationService>()));

However, if that string uri is used in more than one component, you might want to consider hiding that uri behind an abstraction. For instance:

public interface ISomeWebServiceClientProxy {
    Data LoadData();
}

class RealSomeWebServiceClientProxy : ISomeWebServiceClientProxy {
    private readonly string uri;
    public RealSomeWebServiceClientProxy(string uri) {
        this.uri = uri;
    }

    public Data LoadData() {
        // use uri, call web service, return data.
    }
}

This way the OrdersRequestHandler can simply take a dependency on ISomeWebServiceClientProxy instead of the ambiguous string:

public OrdersRequestHandler(ISomeWebServiceClientProxy proxy, 
    IOrderValidationService service) {
    // store dependencies
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top