Deeptechtons
Deeptechtons

Reputation: 11125

Structuremap constructor parameter injection convention

Is there a convention of specifying a value for constructor parameters named with "x". For example do something like below

For any requested dependency, having a constructor parameter named "pathToFile" , provide this value.

I could do this with For syntax and using ctor but cannot write same piece of code for every class that i want to get configured.

public class FileManager(string pathToFile):IDocumentManager
{

}

When ever i request IDocumentManager(dependency) it(instance) has a constructor with parameter named pathToFile so i want it to get injected with some value

Upvotes: 1

Views: 281

Answers (1)

marisks
marisks

Reputation: 1822

It is possible to create custom convention. Create convention by implementing IRegistrationConvention. Then in Process method check if type is concrete type, check if it has required constructor parameter and then register constructor's paremeter for all interfaces it implements and also type itself. I am using such convention to inject connection string.

public class ConnectionStringConvention : IRegistrationConvention
{
    public void Process(Type type, Registry registry)
    {
        if (!type.IsConcrete() || type.IsGenericType) return;

        if (!HasConnectionString(type)) return;

        type.GetInterfaces().Each(@interface =>
        {
            registry.For(@interface)
                .Use(type)
                .WithProperty("connectionString")
                .EqualTo(SiteConfiguration.AppConnectionString);
        });

        registry.For(type)
            .Use(type)
            .WithProperty("connectionString")
            .EqualTo(SiteConfiguration.AppConnectionString);
    }

    private bool HasConnectionString(Type type)
    {
        return type.GetConstructors()
            .Any(c => c.GetParameters()
                .Any(p => p.Name == "connectionString"));
    }
}

After convention created, register it in your container configuration:

Scan(x =>
{
    x.TheCallingAssembly();
    x.WithDefaultConventions();
    x.Convention<ConnectionStringConvention>();
});

For more information check:

http://structuremap.github.io/registration/auto-registration-and-conventions/

http://www.sep.com/sep-blog/2010/06/04/teaching-structuremap-about-c-4-0-optional-parameters-and-default-values/

Upvotes: 1

Related Questions