Simpleinjctor get instance based on generic type - ninject

I need to convert Ninject to SimpleInjector Implementation.
I have the following code
public T Resolve<T>()
{
// IKernel kernel - is the global declaration
return kernel.Get<T>();
}
I want the equivalent to this for simple injector
I have tried
public T Resolve<T>()
{
// SimpleInjector.Container kernel - is the global declaration
return kernel.GetInstance<T>();
}
But this throws an error due to T not being a class as it is a generic type.
I can't cast the method to strictly take and return T as class because it is an interface implementation.
Any Advice?

Either add a generic type constraint to your Resolve method:
public T Resolve<T>() where T : class
{
return kernel.GetInstance<T>();
}
or call the non-generic GetInstance overload:
public T Resolve<T>()
{
return (T)kernel.GetInstance(typeof(T));
}

Related

Class implementing Interface with subtype arguments

Why I cannot do that? I get compilation error.
public interface A {
void update(Object a);
}
public class B implements A{
void update(Long a) {
}
}
That is Java 8
I do not see here violating any OO principle.
That's really make my time difficult to implement a generic API...
(I try to get Generics out of the play because the generic API gets counter-intuitive)
You get a compilation error because void update(Long a) does not implement void update(Object a).
You can implement it as follows:
public class B implements A {
void update(Object o) {
if (!(o instanceof Long)) {
// possibly throw an exception
}
Long a = (Long) o;
...
}
}
A class that implements an interface must implement all the methods declared in the interface. The methods must have the exact same signature (name + parameters) as declared in the interface. The class does not need to implement (declare) the variables of an interface. Only the methods.
Source:
http://tutorials.jenkov.com/java/interfaces.html#:~:text=A%20class%20that%20implements%20an,Only%20the%20methods.

Avoiding instance construction of return type while generating stub for method

I have issue while trying to mock method that returns instance of abstract class with Rhino Mocks. Issue is that MammalBase constructor is invoked while stub is created and I would like to avoid that. All source code in question is locked for editing and only tests can be changed.
Eventually, base class is processing something by type attributes in constructor, and throws exception if no adequate attributes are detected. That causes a extensive logging.
My hope is to remove unnecessary logs from tests.
Is it possible to instruct Rhino Mocks not to instantiate return type (MammalBase) when it creates proxy while creating a stub?
Is explicit attribute or type setting possible for return value while Rhino creates stub for method with abstract class instance as return type?
Is avoiding constructor even possible without making stubbed method return interface?
I found that issue does not exist if:
1. Stubbed method returns array like MammalBase[],
2. Stubbed method returns derivate class like "Human" first, since no more constructors of base class are invoked.
Thanks in advance!
(Code sample)
public interface IDetermineMammalByType
{
MammalBase DetermineMammalByType(MammalBase creature);
}
public abstract class MammalBase
{
protected MammalBase()
{
CustomAttribute[] attributes = (CustomAttribute[])Attribute.GetCustomAttributes(this.GetType(), typeof(CustomAttribute));
if (!attributes.Any(x=> x as CustomAttribute != null))
{
//This causes issue
throw new Exception();
}
}
}
[CustomAttribute()]
public class Human : MammalBase { }
[System.AttributeUsage(System.AttributeTargets.Class |
System.AttributeTargets.Struct)]
public class CustomAttribute : System.Attribute
{
public CustomAttribute() { }
}
public class MammalDetector : IDetermineMammalByType
{
public MammalBase DetermineMammalByType(MammalBase creature)
{
//Some logic
return null;
}
}
//TEST
[TestMethod()]
public void DetermineMammalByTypeTest()
{
IDetermineMammalByType myTest = MockRepository.GenerateStub<IDetermineMammalByType>();
var creature = new Human();
//Here it fails while mocking method
myTest.Stub(x => x.DetermineMammalByType(creature)).Return(new Human());
}

NInject IBindingGenerator and ToProvider

I've created this code:
public class AddonsModule : Ninject.Modules.NinjectModule
{
public override void Load()
{
this.Bind(b => b.FromAssembliesMatching("*")
.SelectAllClasses()
.InheritedFrom(typeof(UIExtensibility.AbstractAddon))
.BindWith(new AddonBindingGenerator())
);
}
private class AddonBindingGenerator : IBindingGenerator
{
public System.Collections.Generic.IEnumerable<Ninject.Syntax.IBindingWhenInNamedWithOrOnSyntax<object>> CreateBindings(System.Type type, Ninject.Syntax.IBindingRoot bindingRoot)
{
if (type.IsInterface || type.IsAbstract)
yield break;
yield return bindingRoot.Bind(type).ToProvider(typeof(UIExtensibility.AbstractAddon));
}
}
private class AddonProvider : IProvider<UIExtensibility.AbstractAddon>
{
public object Create(IContext context)
{
return null;
}
public Type Type
{
get { throw new NotImplementedException(); }
}
}
}
AddonProvider seems be avoided. This is never performed.
When I perform:
kernel.GetAll<UIExtensibility.AbstractAddon>(), AddonProvider.Create method is never performed.
Could you tell me what's wrong?
I'll appreciate a lot your help.
Thanks for all.
AddOnProvider is inheriting from IProvider<T> instead of UIExtensibility.AbstractAddon.
also, you may have issues binding to private inner classes. make AddOnProvider a public top level class.
You're binding a specific type which inherits from typeof(UIExtensibility.AbstractAddon) to a provider. For example, there could be a class Foo : UIExtensibility.AbstractAddon.
Now your convention binding translates to this:
Bind<Foo>().ToProvider<AddonProvider>();
Now, kernel.GetAll<UIExtensibility.AbstractAddon>() however is looking for bindings made like:
Bind<UIExtensibility.AbstractAddon>().To...
Fix It
So what you need to do is change the line
bindingRoot.Bind(type).ToProvider(new AddonProvider());
to:
bindingRoot.Bind(typeof(UIExtensibility.AbstractAddon)).ToProvider<AddonProvider>();
Furthermore
you're line object f = bindingRoot.Bind(type).ToProvider(new AddonProvider()); is never returning the binding (object f).
does UIExtensibility.AbstractAddon implement IProvider?
Thanks for your answer and comments.
I believe the trouble is on I'm not quite figuring out how this "generic" binding process works.
I'm going to try writing my brain steps process out:
I need to bind every AbstractAddon implementation inside addons assemblies folder. So, I think this code is right, but I'm not sure at all.
this.Bind(b => b.FromAssembliesMatching("*")
.SelectAllClasses()
.InheritedFrom(typeof(UIExtensibility.AbstractAddon))
.BindWith(new AddonBindingGenerator())
);
My AbstractAddon is like:
public abstract class AbstractAddon : IAddon
{
private object configuration;
public AbstractAddon(object configuration)
{
this.configuration = configuration;
}
// IAddon interface
public abstract string PluginId { get; }
public abstract string PluginVersion { get; }
public abstract string getCaption(string key);
public abstract Type getConfigurationPanelType();
public abstract System.Windows.Forms.UserControl createConfigurationPanel();
}
I guess I need to:
foreach implementation of `AbstractAddon` found out,
I need to "inject" a configuration object ->
So, I guess I need to set a provider and provide this configuration object.
This would be my main way of thinking in order to solve this problem.
I've changed a bit my first approach. Instead of using a IBindingGenerator class, I've used the next:
public class AddonsModule : Ninject.Modules.NinjectModule
{
public override void Load()
{
this.Bind(b => b.FromAssembliesMatching("*")
.SelectAllClasses()
.InheritedFrom(typeof(UIExtensibility.AbstractAddon))
.BindAllBaseClasses()
.Configure(c => c.InSingletonScope())
);
this.Bind<object>().ToProvider<ConfigurationProvider>()
.WhenTargetHas<UIExtensibility.ConfigurationAttribute>();
}
So, My ConfigurationProvider is:
private class ConfigurationProvider : IProvider<object>
{
public object Create(IContext context)
{
return "configuration settings";
}
}
And now, my AbstractAddon constructor contains the parameter annotated with ConfigurationAttribute as:
public AbstractAddon([Configuration]object configuration)
{
this.configuration = configuration;
}
The problem now, NInject seems to ignore the configuration object provider. NInject generates a dump object, however, not perform ConfigurationProvider.Create method...
What I'm doing wrong, now?
Is this approach really better than the last one?
Thanks for all.

ninject binding for specify class

if I have the interface interfaceA
public interface IInterfaceA
{
void MethodA();
void MethodB();
}
and I have the classA
class ClassA:IInterfaceA
{
public void MethodA()
{
}
public void MethodB()
{
}
}
it's ok that I use ninject's bind,but when it comes that I have a method that called MethodC,I think the method should only exists in classA(just for classA) and should not be defined in InterfaceA,so how to use ninject'bind when just calling like this:
var a = _kernel.get<IInterfaceA>()
should I convert the result into ClassA ? (is that a bad habbit?) or there are another solution
Usually this is needed when you want interface separation but need both interfaces to be implemented by the same object since it holds data relevant to both interfaces. If that is not the case you would be able to separate interfaces and implementation completely - and then you should do so.
For simplicitys sake i'm going to asume Singleton Scope, but you could also use any other scope.
Create two interfaces instead:
public interface IInterfaceA {
{
void MethodA();
}
public interface IInterfaceC {
void MethodC();
}
public class SomeClass : IInterfaceA, IInterfaceC {
....
}
IBindingRoot.Bind<IInterfaceA, IInterfaceB>().To<SomeClass>()
.InSingletonScope();
var instanceOfA = IResolutionRoot.Get<IInterfaceA>();
var instanceOfB = IResolutionRoot.Get<IInterfaceB>();
instanceOfA.Should().Be(instanceOfB);
Does this answer your question?

Ninject factory method with input parameter to determine which implementation to return

I am trying to find a way to have a factory class / method that would take in an object or some kind of identifier (string or type) then based off the input parameter determine which implementation of the interface to create and return.
how do I setup my factory method and register the dependency for the interface? following is what I have roughly.
public class ISampleFactory
{
public ISample GetSample(Type type)
{
// do something here to return an implementation of ISample
}
}
public class SampleA : ISample
{
public void DoSomething();
}
public class SampleB : ISample
{
public void DoSomething();
}
public interface ISample
{
void DoSomethin();
}
Have a look at ninject Contextual Bindings Documentation:
You can either use Named Bindings:
this.Bind<ISample>().To<SampleA>().Named("A");
this.Bind<ISample>().To<SampleB>().Named("B");
or a conditional binding with any of the already available extensions or write your own:
this.Bind<ISample>().To<SampleA>().When(...);
this.Bind<ISample>().To<SampleB>().When(...);
see https://github.com/ninject/ninject/wiki/Contextual-Binding