StructureMap3如何为所有类型配置构造函数字符串注入? [英] StructureMap3 How to configure constructor string injection for all types?
问题描述
我已使用
Scan(
scan => {
scan.TheCallingAssembly();
scan.WithDefaultConventions();
scan.With(new ControllerConvention());
});
但是如何指定构造函数注入,而不必像这样指定具体类型? p>
But how do I specify for constructor injection with out having to specify the concrete type like this?
string connStr = "...";
For<IRepository().Use<MyRepository>().Ctor<string>("connectionString").Is(connStr);
推荐答案
您可以创建用于注册存储库的专用约定。 / p>
You can create dedicated convention for registration of repositories.
public class RepositoryConvention : IRegistrationConvention
{
private const string ConnectionString = "your connection string";
public void Process(Type type, Registry registry)
{
if (type.IsConcrete() && type.GetInterfaces().Contains(typeof(IRepository)))
{
registry.For(typeof(IRepository))
.Use(type)
.CtorDependency<string>("connectionString")
.Is(ConnectionString);
}
}
}
带连接字符串。我打赌你从web / app.config得到它,所以添加抽象访问它将是有帮助的。
or create dedicated type to provide with connection string. I bet you are getting it from web/app.config so adding abstraction for accessing it would be helpful anyway.
public interface IConfigurationSettingsReader
{
string ReadConnectionString(string name);
T ReadSetting<T>(string settingName);
}
然后您只需将其添加为MyRepository的依赖项,需要在注册或使用自定义约定中明确添加。
Then you just add it as a dependency for your MyRepository and you don't need to add it explicitly in registration or use custom convention.
public class MyRepository : IRepository
{
private readonly string connectionString;
public MyRepository(IConfigurationSettingsReader settingsReader)
{
this.connectionString = settingsReader.ReadConnectionString("ConnStrName");
}
}
您可以考虑创建一个抽象基本存储库类
You can consider creating an abstract base repository class to be inherited by each repository to get rid of setup bolerplate.
希望这有助于!
这篇关于StructureMap3如何为所有类型配置构造函数字符串注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!