Question

I am waching the screencast of Funq but I don't understand something with the following lambda in the testing code :

var container = new Container();
container.Register<IBar>(c => new Bar());

the declaration :

public void Register<TService>(Func<Container, TService> factory) { ... }

In the lambda, the new Bar() acts as the TService and the c as the Container for the Func used in Register method.

During the execution, when is this c delcared ? Is it the container created at the beginning because I do not understand when an instance of a Container is passed to the Register method.

Was it helpful?

Solution

During the execution, when is this c declared?

You did, using the following line:

var container = new Container();

Funq in fact passes an instance to itself to the supplied delegate. This allows you, for instance, to do the following:

container.Register<IBar>(c => 
{
    var bar = c.Resolve<Bar>();
    bar.SomeProperty = 5;
    return bar;
});

However, passing the container itself to the delegate it quite useless IMO, since this value is always available during registration. For instance, you can also write this:

container.Register<IBar>(unused => 
{
    var bar = container.Resolve<Bar>();
    bar.SomeProperty = 5;
    return bar;
});

In other words, it would have been much easier if the Register method accepted a Func<T> instead of a Func<Container, T>. The previous snippet would have looked like this:

container.Register<IBar>(() => 
{
    var bar = container.Resolve<Bar>();
    bar.SomeProperty = 5;
    return bar;
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top