3

I am trying to inject multiple instances of the same class in a constructor. However when they are resolved they always resolve as the same instance. Here is my registration code:

public Repository(Class1 class1, Class1 class2)
{
    _class1 = class1;
    _class2 = class2;
}

builder.Register(ctx => new Class1()).Named<Class1>("a");

builder.Register(ctx => new Class1()).Named<Class1>("b");

builder.RegisterType<Repository>().WithParameters(new[]
{
    new ResolvedParameter((p, c) => p.Name == "a", (p, c) => c.ResolveNamed<Class1>("a")),
    new ResolvedParameter((p, c) => p.Name == "b", (p, c) => c.ResolveNamed<Class1>("b"))
}).AsImplementedInterfaces();

However when I do this I get the same instance of Class1 in the Repository.

Bill Posters
  • 1,079
  • 2
  • 12
  • 16
  • What is `Class1` and should it really be injected? – Aron Jul 29 '16 at 04:22
  • 1
    Why are they injected at all?! Where you get the Credentials forms part of the business logic. Injection is not for business logic. By using injection, you are hiding critical information on how your application works. Injection is for hiding plumbing... – Aron Jul 29 '16 at 04:48
  • 2
    Imagine for a moment that it is a good idea!!....I just want to know if it can be done with Autofac and if so how to go about it. – Bill Posters Jul 29 '16 at 04:53
  • 1
    Without a more concrete reason for your requirements, I can only advise where you can look. Try looking at the code here http://docs.autofac.org/en/latest/examples/log4net.html Even so. I think you are making a massive maintainability mistake. – Aron Jul 29 '16 at 04:58
  • Your code works as expected : https://dotnetfiddle.net/ncvexM – Cyril Durand Jul 29 '16 at 07:06
  • 1
    In the snippet posted, the repository ctor params are "class1" and "class2" - but the ResolvedParameters are "a" and "b". They have to match. – Travis Illig Jul 29 '16 at 12:49
  • When I try to [replicate](https://dotnetfiddle.net/HVhcIU) your example, I always get a new instance of `Class1` and not identical ones as you said. Maybe your example is missing something crucial? – fknx Jul 29 '16 at 14:20

0 Answers0