Jim Foye
Jim Foye

Reputation: 2036

Mapping dependency to property of existing component

Is there a shortcut for specifying that a dependency maps to a property on an object already in the container? I know I can write a factory method to do this, just wondering if there is a more elegant way.

I can specify that component A has a dependency that maps to an instance of component B, by naming A and then writing the installer for B like this:

container.Register(Component.For<IMdiController>()
                        .ImplementedBy<MdiController>()
                        .DependsOn(Dependency.OnComponent("shell", "shell")));

In this example, imagine that the dependency "shell" maps not to the component "shell", but rather a property of that component (e.g., "shell.SomeProperty" - I tried this dot syntax already and it doesn't work).

Upvotes: 1

Views: 257

Answers (1)

kmp
kmp

Reputation: 10865

I may not have understood your question correctly but perhaps what you want is a dynamic parameter here.

Here is a description of this property from the docs:

There are times where you need to supply a dependency, which will not be known until the creation time of the component. For example, say you need a creation timestamp for your service. You know how to obtain it at the time of registration, but you don't know what its specific value will be (and indeed it will be different each time you create a new instance). In this scenarios you use DynamicParameters method.

In your case you could do something like the following so that the SomeProperty property would be called on the Shell component resolved from the container in order to get the value for the something dependency.

container.Register(
    Component
        .For<IMdiController>()
        .ImplementedBy<MdiController>()
        .DynamicParameters((k, d) => d["something"] = k.Resolve<Shell>().SomeProperty));

I am not sure if there are implications to you in calling resolve like this but maybe it is fine.

Upvotes: 1

Related Questions