如果我有这样的话:
var container = new Container();
container.RegisterInstance("a", serviceKey: "a");
container.RegisterInstance("b", serviceKey: "b");
如何注册一个字符串列表,其中包含" a"和" b"?
我也尝试使用params,但没有成功。
class T
{
public string[] x;
public T(string s, params string[] strs)
{
x = (new[] {s}).Union(strs).ToArray();
}
}
static void Main(string[] args)
{
var container = new Container();
container.RegisterInstance("a", serviceKey: "a");
container.RegisterInstance("b", serviceKey: "b");
container.Register<T>(made: Made.Of(() => new T(Arg.Of<string>("a"))));
container.Register<T>(made: Made.Of(() => new T(Arg.Of<string>("a"), Arg.Of<string>("b"))));
编辑:
我设法让它运行,但它可能不是一个好的工作场所:
container.RegisterInstance(typeof(IEntityManager), (IEntityManager)ctx.GetObject("entityManager_candidate"), serviceKey: "candidate");
container.RegisterInstance("XYZ_CANDIDATE", serviceKey: "candidate");
container.Register<IDalCandidate>(serviceKey: "candidate",
made: Made.Of(() => new DalCandidate(Arg.Of<IEntityManager>("candidate"), Arg.Of<string>("candidate"))));
container.RegisterInstance(typeof(IEntityManager), (IEntityManager)ctx.GetObject("entityManager_resource"), serviceKey: "resource");
container.RegisterInstance("XYZ_RESOURCE", serviceKey: "resource");
container.Register<IDalCandidate>(serviceKey: "resource",
made: Made.Of(() => new DalCandidate(Arg.Of<IEntityManager>("resource"), Arg.Of<string>("resource"))));
//container.RegisterMapping<IDalCandidate, DalCandidate>()
var lst = new List<IDalCandidate>
{
container.Resolve<IDalCandidate>("resource"),
container.Resolve<IDalCandidate>("candidate")
};
container.RegisterInstance(typeof(IList<IDalCandidate>), lst);
container.Register<ISearchWeightedCandidateManager, SearchWeightedCandidateManager>();
答案 0 :(得分:1)
更新:更好的回答
再次查看您的样本..基本上您有某种多租户,然后在一些消费者中注入所有租户。
c.Register<Dal>(serviceKey: "x");
c.Register<Dal>(serviceKey: "y");
// using delegate for brevity, better convert to method
Func<object, Func<RequestInfo, bool>> getCondition =
key => r => r.Parent.Enumerate().Any(p => p.ServiceKey == key);
var inX = getCondition("x");
var inY = getCondition("y");
c.RegisterInstance("a", condition: inX);
c.RegisterInstance("b", condition: inY);
// register the rest of dependencies in X or in Y
c.Register<Manager>(); // normally injects Dal[]
那证明了这个想法。希望它比你的第一个答案更适合你的情况。