Swinject: generate instances of any object (for not registered object, ViewModel, etc...) - swift

is possible to resolve/ create a new instace of object thats are not registered in Swinject container? In Unity dependency injection for c# (from Microsoft) is it.
I Want to resolve viewModel class, that have dependence for some protocols.
For example:
I have registred IFileManager in container:
container.register(IFileManager.self) { _ in FileManager() }.inObjectScope(ObjectScope.container)
and me viewModel have dependece for IFileManager
class AwesomeViewModel{
init (fileManager: IFileManager) {
....
}}
now i want to create new instance of AwesomeViewModel using Swinject resolver, and I want all the dependencies to be added to the init, but it doesn't work
viewModel = AppDelegate.container.resolve(AwesomeViewModel.self)
and ViewModel is nil

No, Swinject is not able to infer which initialisation method you expect to be used for instantiation of AwesomeViewModel. You need to explicitly define it first:
container.register(AwesomeViewModel.self) {
AwesomeViewModel(fileManager: $0.resolve(IFileManager.self)!)
}
Admittedly, this might get quite cumbersome if you have classes with many dependencies. If that becomes a problem, I suggest you check out the SwinjectAutoregistration extension. It enables you to write:
container.autoregister(AwesomeViewModel.self, initializer: AwesomeViewModel.init)

Related

How to call constructor with interface arguments when mocking a concrete class with Moq

I have the following class, which uses constructor injection:
public class Service : IService
{
public Service(IRepository repository, IProvider provider) { ... }
}
For most methods in this class, I simply create Moq mocks for IRepository and IProvider and construct the Service. However, there is one method in the class that calls several other methods in the same class. For testing this method, instead of testing all those methods together, I want to test that the method calls those methods correctly and processes their return values correctly.
The best way to do this is to mock Service. I've mocked concrete classes with Moq before without issue. I've even mocked concrete classes that require constructor arguments with Moq without issue. However, this is the first time I've needed to pass mocked arguments into the constructor for a mocked object. Naturally, I tried to do it this way:
var repository = new Mock<IRepository>();
var provider = new Mock<IProvider>();
var service = new Mock<Service>(repository.Object, provider.Object);
However, that does not work. Instead, I get the following error:
Castle.DynamicProxy.InvalidProxyConstructorArgumentsException : Can not instantiate proxy of class: My.Namespace.Service.
Could not find a constructor that would match given arguments:
Castle.Proxies.IRepository
Castle.Proxies.IProvider
This works fine if Service's constructor takes simple arguments like ints and strings, but not if it takes interfaces that I'm mocking. How do you do this?
Why are you mocking the service you are testing? If you are wishing to test the implementation of the Service class (whether that be calls to mocked objects or not), all you need are mocks for the two interfaces, not the test class.
Instead of:
var repository = new Mock<IRepository>();
var provider = new Mock<IProvider>();
var service = new Mock<Service>(repository.Object, provider.Object);
Shouldn't it be this instead?
var repository = new Mock<IRepository>();
var provider = new Mock<IProvider>();
var service = new Service(repository.Object, provider.Object);
I realize that it is possible to mock concrete objects in some frameworks, but what is your intended purpose? The idea behind mocking something is to remove the actual implementation so that it does not influence your test. But in your question, you have stated that you wish to know that certain classes are called on properly, and then you wish to validate the results of those actions. That is undoubtedly testing the implementation, and for that reason, I am having a hard time seeing the goals of mocking the concrete object.
I had a very similar problem when my equivalent of Service had an internal constructor, so it was not visible to Moq.
I added
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
to my AssemblyInfo.cs file for the implementing project. Not sure if it is relevant, but I wanted to add a suggestion on the off chance that it helps you or someone else.
It must be old version issue, all is ok with latest version. Nick, Please check!
P.s.: I started bounty by misstake (I had wrong signature in my constructor).

Approach for binding on a MVVM application using Portable Class Libraries

I'm trying to port the core of an application across to Portable Class Libraries and don't appear to have binding support.
I'm trying to bind a property on my ViewModel to my Model, which consists of an ObservableDictionary (INotifyPropertyChanged, INotifyCollectionChanged, IDictionary<string, string>). I do this usually (with WP7) by using the following code when initialising the view model:
SetBinding(MyProperty, new Binding(string.Format("MyDictionary[{0}]", "thekey")) { Source = MyModel });
How would I approach this when using Portable Class Libraries, where it seems like the Binding class is unavailable?
I've implemented this by having the base class for the ViewModels wire up to the PropertyChanged event of the ViewModel and the NotifyCollectionChanged event of the ObservableDictionary. I then have a method (with a set of overloads for additionally supplying an implementation of an IPclValueConverter which is a copy of the IValueConverter) which adds to a collection of PclBinding objects which is a set of PropertyInfo, dictionary key, IPclValueConverter and a converter parameter.
Within the PropertyChanged/NotifyCollectionChanged I check to see if the binding should be updated, and if so perform the update passing the value through a converter if present.
This means that from my original example, I now write the following inside my ViewModel which creates the binding as required:
SetBinding(() => MyProperty, "theKey");
If anyone is actually interested in this code I'd be happy to post it up. :)

Unity IoC Explicitly ask container for new instance

It appears that Unity IoC defaults to creating a new instance of an object when it resolves a type. But my question is there someway to be explicit and tell my container that whenever I have it resolve an object type to give me a new instance of said type?
IE i want to be explicit and force the container to make sure theInstance is a new instance each time it resolves type:MyNewObject (or all types for that matter)
MyNewObject theInstance = container.Resolve<MyNewObject>();
Yes it is easily configurable by a TransientLifetimeManager
When you register a class should have something like
container.Register<IMyNewObject, MyMewObject>(new TransientLifetimeManager());
//or
container.Register<MyMewObject>(new TransientLifetimeManager())
If you're applying IoC principles properly, your class declares its dependencies and then the container handles the lifecycles of them. For example, you want to grab an HttpRequest object and the container handles providing the current thread-local one, or whatever.
Your code shouldn't really have to care about the life-cycle of its dependencies, as it should never be responsible for clearing up after them or what-have-you (all of that should be encapsulated in the dependency itself, and invoked by the container when it is shut down).
However, if you do need to care in your code about whether you get a singleton instance or a per-injected instance of the same type, I like to be explicit about it by using the type system itself, just as the Guice container for Java does with its Provider pattern. I've created a Guice-style IProvider<T> interface that I use to do this, and I just wire it up with a simple static factory method for them like so:
Provider.Of<Foo>(() => { /* Code to return a Foo goes here */})

Unity Registration: Hooking up an interface to a pre-registered concrete class

I already have a concrete class registered in my unity container and I want to, later on, register an interface that hooks up to that class but uses the existing registration.
I can do this using the following code but it causes a resolve at registration time...
container.RegisterInstance<IMyClass>(container.Resolve<MyClass>());
Is it possible to hook the code up with all resolution done at the point the interface is resolved?
The trick is to use an InjectionFactory:
container.Register<IMyClass>(
new InjectionFactory(c => c.Resolve<MyClass>()));
It sounds like you want to create a factory type. Here, a Func delegate type is used to avoid the creation of a new custom factory type:
container.RegisterInstance<Func<IMyClass>>(() => container.Resolve<MyClass>());
Your other types can then take a dependency on this factory:
private IMyClass myClass;
public MyOtherType(Func<IMyClass> myClassFactory)
{
this.myClass = myClassFactory();
}
IUnityContainer container = new UnityContainer();
var onlyInstance = new MyClass();
container.RegisterInstance<IMyClass>(onlyInstance);
IMyClass resolved = container.Resolve<IMyClass>();
if (object.ReferenceEquals(onlyInstance, resolved))
{
Console.WriteLine("Equal");
}
This prints "Equal". This is the way I would register the instance in the first place.
In a comment above, you imply that you do not control the initial registration. That's the real issue. I would recommend going down one of the following paths (in order of preference, highest to lowest):
Create your own UnityContainer independent of the pre-registered one
Create a child container with CreateChildContainer
Use named (non-default) mappings

StructureMap IoC problem getting the instance in runtime

i have 2 concrete types "CategoryFilter" & "StopWordsFilter" that implements
"IWordTokensFilter".
Below is my setup:
ForRequestedType<IWordTokensFilter>().TheDefaultIsConcreteType<CategoryFilter>()
.AddInstances(x =>
{
x.OfConcreteType<StopWordsFilter>();
}
);
The problem is the run-time when structure map auto inject it on my class, bec. i have arguments with same plugin-type:
public ClassA(IWordTokensFilter stopWordsFilter, IWordTokensFilter categoryFilter)
i'm always getting CategoryFilter in my first argument but it should be stopWordsFilter.
How can i setup this in a right way? thanks in advance
There are a number of possible solutions:
1) Does ClassA need to differentiate between the filters, or does it just need to run them both? If not, you can change the constructor to accept an array, which will cause all registered instances of IWordTokensFilter to be injected:
public ClassA(IWordTokensFilter[] filters)
You can then foreach over the filters to apply them.
2) If you do need to differentiate them, because they need to be used differently, you may consider having one implement a marker interface the better describes its purpose. ClassA could then be changed to take in an IWordTokensFilter and an ICategoryFilter (or whatever you name the marker interface). Register CategoryFilter with ICategoryFilter and then both will be injected properly.
public ClassA(IWordTokensFilter stopWordsFilter, ICategoryFilter categoryFilter)
3) You can tell StructureMap explicitly how to create ClassA:
ForRequestedType<ClassA>().TheDefault.Is.ConstructedBy(c => {
return new ClassA(c.GetInstance<StopWordsFilter>(), c.GetInstance<CategoryFilter>());
});
4) You can tell StructureMap to override one of the dependencies for ClassA:
x.ForRequestedType<ClassA>().TheDefault.Is.OfConcreteType<ClassA>()
.CtorDependency<IWordTokensFilter>("stopWordsFilter").Is<StopWordsFilter>();