如何统一将字符串注入 类
How can I inject a string into my classes with unity
我有很多 class 这样的 public class GetA:IGetA{}
public class GetB:IGetB{}
等等,都在一个特定的命名空间中
我用这样的代码块注册它们
container.RegisterTypes(
AllClasses.FromLoadedAssemblies().Where(
t => t.Namespace == "Getters"),
WithMappings.FromMatchingInterface,
WithName.Default,
WithLifetime.ContainerControlled);
这非常有效。
我现在不得不向其中一些人介绍对某个字符串的依赖。
public class GetA:IGetA
{
public GetA(string separator){}
}
分隔符对于所有需要它的 classes 都是相同的。我如何最好地注入这种依赖性?
我应该注入工厂 class 吗?这似乎比我想要的要复杂!
这可能是一个恐怖的场景,但这是我所做的...
我已经让我的 getter class 依赖于 Func<string>
public class GetA : IGetA
{
private readonly string separator;
public GetA(Func<string> separator){
this.separator = separator();
}
}
然后在我的 UnityConfig.cs
我已经把
container.RegisterType<Func<string>>(
new InjectionFactory(f => new Func<string>(() => "The separator... really it comes from a database call though")
));
在我的测试中我可以做到
new GetA (() => ", ");
这可能看起来有点古怪,但让我与获取分隔符的数据库调用分开..
我对此不是很满意,好像我想要 Func<string>
别处那样我会踩到我的脚趾。也许我确实需要 IGetSeperatorFactory
但我不想要!
我有很多 class 这样的 public class GetA:IGetA{}
public class GetB:IGetB{}
等等,都在一个特定的命名空间中
我用这样的代码块注册它们
container.RegisterTypes(
AllClasses.FromLoadedAssemblies().Where(
t => t.Namespace == "Getters"),
WithMappings.FromMatchingInterface,
WithName.Default,
WithLifetime.ContainerControlled);
这非常有效。
我现在不得不向其中一些人介绍对某个字符串的依赖。
public class GetA:IGetA
{
public GetA(string separator){}
}
分隔符对于所有需要它的 classes 都是相同的。我如何最好地注入这种依赖性?
我应该注入工厂 class 吗?这似乎比我想要的要复杂!
这可能是一个恐怖的场景,但这是我所做的...
我已经让我的 getter class 依赖于 Func<string>
public class GetA : IGetA
{
private readonly string separator;
public GetA(Func<string> separator){
this.separator = separator();
}
}
然后在我的 UnityConfig.cs
我已经把
container.RegisterType<Func<string>>(
new InjectionFactory(f => new Func<string>(() => "The separator... really it comes from a database call though")
));
在我的测试中我可以做到
new GetA (() => ", ");
这可能看起来有点古怪,但让我与获取分隔符的数据库调用分开..
我对此不是很满意,好像我想要 Func<string>
别处那样我会踩到我的脚趾。也许我确实需要 IGetSeperatorFactory
但我不想要!