MVVM-Light SimpleIoc: Can't create multiple instances dynamically - mvvm-light

I am building an WPF application using the MVVM Light Toolkit and specifically SimpleIoc.
I have a parent viewmodel that dynamically creates child viewmodels. When doing this I am using "standard" dependency injection to pass a IConfigService as a parameter to the constructor. I want the IConfigService to be a unique instance for each child viewmodel. So I try this:
IConfigService service = SimpleIoc.Default.GetInstance<IConfigService>(key);
ChildViewModel vm = new ChildViewModel(service);
Where key is a unique identifier for each child viewmodel. According to the documentation of MVVM Light and SimpleIoc this GetInstance method:
...provides a way to get an instance of a given type corresponding to a given key. If no instance had been instantiated with this key before, a new instance will be created.
There is also a remark that the class must have been registered before, else it returns null. In my case it has been, in ViewModelLocator:
var configService = new ConfigService();
SimpleIoc.Default.Register<IConfigService>(() => configService);
However, the GetInstance call returns the same instance every time.
What am I doing wrong here?

You registered an already instantiated object.
SimpleIoc does not create its own instances with this overload. It always returns configService. Either you need to perform the instantiation within the lambda, because you are using a factory overload, or you can do this more easily by just passing the ConfigService type. SimpleIoc will take care of the instantiation itself.

Related

What does it mean when saying "to be assigned something"| ASP.NET Core

I was reading a book about Learning ASP.NET Core API when I run to a part saying:
We create a private read-only field _repository that will be assigned
the injected MockCommandAPIRepo object in our constructor and used
throughout the rest of our code.
Here is some text I thought you'd better have:
Then there are some explanations related to the picture above:
Add the new using statement to reference ICommandAPIRepo.
We create a private read-only field _repository that will be assigned the injected MockCommandAPIRepo object in our constructor
and used throughout the rest of our code.
The Class constructor will be called when we want to make use of our Controller.
At the point when the constructor is called, the DI system will spring into action and inject the required dependency when we ask for
an instance of ICommandAPIRepo. This is Constructor Dependency
Injection.
We assign the injected dependency (in this case MockCommandAPIRepo) to our private field (see point 1).
And that’s pretty much it! We can then use _repository to make use of our
concrete implementation class, in this case MockCommandAPIRepo. As
I’ve stated earlier, we’ll reuse this pattern multiple times through
the rest of the tutorial; you’ll also see it everywhere in code in
other projects – take note.
Now, According to the highlighted part above in number 2, I got a little confused!
I've heard of "to be assigned by some value" before, but here, it is saying that:
that will be assigned the injected MockCommandAPIRepo object in our constructor
and as you see, there is no "by" added before the injected MockCommandAPIRepo object....
So, I have a question now. What does it mean by the highlighted part above in number 2?
Does it mean the same when we add "by" in the sentence? or not?
This is about dependency injection in Asp.Net Core. After we register service to the IOC Container, How to use it in our controller? We can inject them in controller via Constructor Injection. Once we register a service, the IoC container automatically performs constructor injection if a service type is included as a parameter in a constructor. In your question, An IoC container will automatically pass an instance of ICommandAPIRepo(MockCommandAPIRepo) to the constructor of CommandsController. Now we can use MockCommandAPIRepo in the constructor. But it can only be used in constructor, How can we use it in other method in CommandsController? Here we use:
private readonly ICommandAPIRepo _repository;
to create a global variable in CommandsController, Then in constructor, We use:
_repository = repository
assign the value of repository to _repository. Now _repository and repository has the same value, Because _repository is a global variable, So We can use _repository in other method in CommandsController. The whole process of dependency injection is done.

What is the proper way to inject (via constructor) different types that implement that same interface?

For example, let's say I have an interface 'IFeed' and two concrete types ('Feed1' and 'Feed2') that implement this interface. Now let's say I have a 'FeedManager' type that takes multiple parameters that will get resolved dynamically, two of which are of type 'IFeed' and I'd like both concrete type to be injected via constructor injection, not via manual resolve (I only use resolve once at the composition root). I have a feeling that I should be using a factory but I wanted to see what the proper way of doing this might be. Many thanks in advance.
If you want ALL implementations of IFeed, you can use array syntax in your constructor and then nothing special is needed at type registration time.
container.RegisterType<IFeedManager, FeedManager>();
container.RegisterType<IFeed, FeedA>("FeedA"); // The name doesn't matter
container.RegisterType<IFeed, FeedB>("FeedB"); // The name doesn't matter
Then the manager constructor...
public FeedManager(IFeed[] feeds) {...}
or if you want to add a little flare for calling the constructor directly...
public FeedManager(params IFeed[] feeds) {...}
Assuming you want to determine the actual concrete instances at runtime, you need to use named type registrations and then tell unity which one you want. So, use a factory method to construct the types required and pass those in as parameter overrides. Unity will use the overrides and resolve any remaining dependencies.
// register the types using named registrations
container.RegisterType<IFeedManager,FeedManager>()
container.RegisterType<IFeed, Feed1>("Feed1")
container.RegisterType<IFeed, Feed2>("Feed2")
Assuming your feed manager has the following named constructor parameters
class FeedManager : IFeedManager
{
public FeedManager (IFeed Feed1, IFeed Feed2, string someOtherDependency)
{
}
}
and create your feed manager:
static IFeedManager CreateFeedManager()
{
ParameterOverride feed1 = new ParameterOverride("Feed1"
,_container.Resolve<IFeed>("feed1"));
ParameterOverride feed2 = new DependencyOverride("Feed2"
,_container.Resolve<IFeed>("feed2"));
IFeedManager = _container.Resolve<IFeedManager>(feed1,feed2)
return IFeedManager;
}
Obviously this is overly simplified, but you you insert your own logic to determine which instance is to be resolved and then injected for each of the IFeed instances required by the FeedManager.
With Unity you would do this like so:
container.RegisterType<IFeed, Feed1>("Feed1");
container.RegisterType<IFeed, Feed2>("Feed2");
container.RegisterType<FeedManager>(new InjectionConstructor(new ResolvedParameter<IFeed>("Feed1"),
new ResolvedParameter<IFeed>("Feed2")));
This has now configured Unity so that when it needs to resolve a FeedManager, it will resolve Feed1 for the first parameter and Feed2 for the second parameter.

Workflow: Trying to pass an object variable to a class method

I am having a tough time trying to pass a parameter into my method when I go to invoke it.
I new up a variable called setupNewCase, then I populate it with data. Once I do that, I then try to invoke the method. It normally works when I don't have a value to pass into it, but it doesn't work here in this case as I am trying to pass something into it.
To pass parameters to the invoked method you use the Parameters property on the InvokeMethod activity. Its available on the activity's properties grid and not directly on the designer.
You would use TargetObject when invoking a method on an instance object but since your CommonMethods class is static you won't ever instantiate it and therefore TargetObject should be empty.

How does ninject work at a high level, how does it intercept object instantiation?

At a high level, how do these dep. injection frameworks work?
I can understand if you always instantiate an object via a custom factory like:
IUser user = DepInjector.Get<User>();
I'm guessing what happens is, wherever you defined the mappings, it will look at the type you want and try and find a match, if found, it will via reflection instantiate the type.
Are there dep. inj. frameworks that would work like:
IUser user = new User();
If so, how would it get the correct user, where is it hooking into the CLR to do this? In case of an asp.net website, is it any different?
If you want to know how Ninject works then the obvious place to start would be reading How Injection Works on their official wiki. It does use reflection but it now also uses dynamic methods:
"By default, the StandardKernel will
create dynamic methods (via
System.Reflection.Emit.DynamicMethod)
that can be used to inject values into
the different injection targets. These
dynamic methods are then triggered via
delegate calls."
As for you second example, I don't believe there are any DI frameworks that would do what you ask. However, constructor injection tends to be most common way of implementing IoC, so that when a class is constructed it knows what type to bind to via some configuration binding. So in your example IUser would be mapped to concrete User in config bindings so that any consuming class that has an IUser parameter as part of its constructor would get the correct User type passed in.
AFAIK there's no way to "hook into" object instantiation with the CLR. The only way to use DI in the second case would be to employ an assembly rewriter (i.e. a postprocessor similar to PostSharp) to replace the call to new with a call to the DI factory method (i.e. GetUser) in the compiled code.

Unity and constructors

Is it possible to make unity try all defined constructors starting with the one with most arguments down to the least specific one (the default constructor)?
Edit
What I mean:
foreach (var constructor in concrete.GetConstructorsOrderByParameterCount())
{
if(CanFulfilDependencies(constructor))
{
UseConstructor(constructor);
break;
}
}
I don't want Unity to only try the constructor with most parameters. I want it to continue trying until it finds a suitable constructor. If Unity doesn't provide this behavior by default, is it possible to create an extension or something to be able to do this?
Edit 2
I got a class with two constructors:
public class MyConcrete : ISomeInterface
{
public MyConcrete (IDepend1 dep, IDepend2 dep2)
{}
public MyConcrete(IDepend1 dep)
{}
}
The class exists in a library which is used by multiple projects. In this project I want to use second constructor. But Unity stops since it can't fulfill the dependencies by the first constructor. And I do not want to change the class since the first constructor is used by DI in other projects.
Hence the need for Unity to try resolving all constructors.
Unity will choose the constructor with the most parameters unless you explicitly tag a constructor with the [InjectionConstructor] attribute which would then define the constructor for Unity to use.
When you state a suitable constructor; that is somewhat contingent on the environment. If for instance you always want to guarantee that a certain constructor is used when making use of Unity use the attribute mentioned previously, otherwise explicitly call the constructor you want to use.
What would be the point of Unity "trying" all constructors? It's purpose is to provide an instance of a type in a decoupled manner. Why would it iterate through the constructors if any constructor will create an instance of the type?
EDIT:
You could allow the constructor with the most params to be used within the project that does not have a reference to that type within its container by making use of a child container. This will not force the use of the constructor with a single param but it will allow the constructor with 2 params to work across the projects now.
You could also switch to using the single constructor across the board and force the other interface in via another form of DI (Property Injection), not Constructor Injection...therefore the base is applicable across the projects which would make more sense.

Resources