Structuremap构造函数参数注入约定

时间:2014-10-08 09:41:01

标签: structuremap convention

是否存在为使用" x"命名的构造函数参数指定值的约定。例如,执行以下操作

对于任何请求的依赖项,具有名为" pathToFile"的构造函数参数; ,提供这个价值。

我可以使用For语法并使用ctor执行此操作,但无法为我想要配置的每个类编写相同的代码段。

public class FileManager(string pathToFile):IDocumentManager
{

}

当我请求IDocumentManager(依赖)时,它(实例)有一个名为pathToFile的参数的构造函数,所以我希望它注入一些值

1 个答案:

答案 0 :(得分:1)

可以创建自定义约定。通过实施IRegistrationConvention创建约定。然后在Process方法中检查类型是否为具体类型,检查它是否具有所需的构造函数参数,然后为其实现的所有接口注册构造函数的参数,并键入自身。我正在使用这种约定来注入连接字符串。

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"));
    }
}

创建约定后,将其注册到容器配置中:

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

有关详细信息,请查看:

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/

相关问题