How to use Ninject in constructor injection of a type in an external assembly - assemblies

I am loading a type from an external assembly and want to create an instance of the type. However, this type/class is setup for constructor injection by objects currently being managed/bound by Ninject. How can I use Ninject to create an instance of this type and inject any constructor dependencies?
Below is how I get this type.
Assembly myAssembly = Assembly.LoadFrom("MyAssembly.dll");
Type type = myAssembly.GetType("IMyType");

Assuming you've created a Kernel, you should be able to create and have it resolved via:
kernel.Get(type)
.... then I read the question.... Assuming MyAssembly.dll has an implementation of IMyType, you need (in your main assembly) :-
kernel.Load( "MyAssembly.dll")
And in your dynamically loaded assembly:-
public class Module : StandardModule
{
public override void Load()
{
Bind<IMyType>().To<MyType>();
}
}
And dont forget to see if MEF is the answer here, as you dont want to go writing reams of explicit plugin management and/or detection logic if you can help it (but if you're just doing straightforward stuff and are only doing the Assembly.LoadFrom() for the purposes of asking the question, you're probably still in Ninject's sweet spot.
Ditto, if you actually need to resolve an interface via Assembly.GetType(), you probably should be using something like dynamic to do the late binding you'll probably have to do (and before you know it you should be using a dynamic language or hosting a scriopting language)

Related

Dependency injection using PRISM Xamarin Forms doesn't work

I have a problem with dependency injection in my project. I use PRISM framework in my project and I chose Ioc container when create it. Link -> https://github.com/blackpantific/InstagroomEX
In my app.xaml file I associate the class and interface
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterForNavigation();
containerRegistry.RegisterForNavigation<WelcomeView, WelcomeViewModel>();
containerRegistry.RegisterForNavigation<RegistrationView, RegistrationViewModel>();
containerRegistry.RegisterForNavigation<LoginView, LoginViewModel>();
//regestering
containerRegistry.RegisterSingleton<IValidationService, ValidationService>();
}
But my page after initializing() doesn't appear at the screen. This is ViewModel constructor
public RegistrationViewModel(INavigationService navigationService, IUserDataService userDataService,
IValidationService validationService) :
base(navigationService)
{
_userDataService = userDataService;
_validationService = validationService;
}
Something wrong here. When I pass to the RegistrationViewModel() constructor another parameters besides INavigationService navigationService the RegistrationView page doesn't not displayed. What am I doing wrong?
Assuming that WelcomePage is displayed correctly and RegistrationPage is not, I think that Andres Castro is correct: Prism tries to resolve the IUserDataService which is not possible. In the debug output you should see a message that IUserDataService cannot be resolved.
(Note: The following is based on my experiences with Prism and Unity. This might hold for other Dependency Injection frameworks, but it's possible that other frameworks behave differently.)
Prism relies on a Dependency Injection (DI) framework, for example Microsofts Unity application block. What happens when you try to navigate to RegistrationPage is, that Prism (if you are using ViewModelLocator.AutowireViewModel="True") tries to determine the type of the viewmodel (by convention) and asks the underlying DI framework to resolve this type (i.e. create an instance). For each of the required constructors parameters of this type, then again the DI framework tries to resolve them. If the parameters require concrete types it will then try to resolve those. If the parametery require interface (or abstract) types, the DI framework will look at its registrations and if the types have been registered create instances according to this registrations (which in turn might involve resolving other types).
If - however - the parameter requires an interface type which has not been registered, the DI framework does not know how to handle the situation. It coulld of course assume null, but this might lead to errors that might be way harder to track down, hence it will throw an exception (which is swallowed and Logged by Prism).
Now how can you handle the situation?
You'll need to tell the DI framework how to resolve IUserDataInterface. Since RegistrationPageViewModel does not actually use it, you could register null
containerRegistry.RegisterInstance<IValidationService>(null);
Could be irritating later, though. I'd rather remove the dependency of RegistrationPageViewModel to IUserDataService altogether - for now and add it later when it's actually used - or create a mock/stub that implements IUserDataService and is used as long there is no real implementation. This would be registered with the DI framework as you did with IValidationService.

ASP.Net MVC 6: Recursive Dependency Injection

Still exploring the new ASP.NET MVC5, now with build in DI!
No Problem so far, I can just inject my Handlers (I don't like the Term Service, since this defines to me a Platform-Neutral Interface):
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddApplicationInsightsTelemetry(Configuration);
services.Configure<Model.Meta.AppSettings>(Configuration.GetSection("AppSettings"));
services.AddSingleton(typeof(Logic.UserEndPointConfigurationHandler));
services.AddSingleton(typeof(Logic.NetworkHandler));
services.AddMvc();
}
Works fine, also the strongly typed Configuration-Object "AppSettings" works perfectly fine.
Also the Injection in the Controllers works as well.
But now my collaps: I seperated my DataAccess from the Handlers, and obviously I'd like to inject them as well:
public class UserEndPointConfigurationHandler
{
private readonly DataAccess.UserEndPointAccess _access;
public UserEndPointConfigurationHandler(DataAccess.UserEndPointAccess access)
{
_access = access;
}
But bam, UserEndPointAccess can't be resolved. So it seems like even I directly request to DI an Class with a Parameterless-Constructor, I need to register that. For this case, sure I should Interface and register them, but what does that mean for internal helper classes I also inject?
According to the Docs: http://docs.asp.net/en/latest/fundamentals/dependency-injection.html#recommendations and also the examples I found, all people in the world only seem to communicate between Controllers and some Repositories. No Business-Layer and no Classes on different Abstraction-Levels in Assemblies.
Is the Microsoft DI approach something totally differnt than the good ol' Unity one, where I can really decouple as fine granular as I'd like to?
Thanks in advance.
Matthias
Edit #Nightowl: I add my answer here, since it's a bit longer.
First of all, Unity does automatically create Instances, if I request a conecrete Type. This allows me to inject Types I register and Types, like Helper classes etc. I don't need to. This combination allows me to use DI everywhere.
Also in your Example I'd need to know the DataAcces in the WebGui, which is quite thight coupled. Well, I know there are solutions for this via Reflection, but I hoped Microsoft did something in this Topic, but probably that'd mean to big of a change.
Also allows Unity to store Instances or Instructions how to create them, another huge feature, which is missing at the moment.
Probably I'm just to spoiled, what refined DI-Libraries do, probably they also do to much, but at the moment the Microsoft-Implementation is just a huge downgrade according to my Information.
MVC Core follows the the composition root pattern, which is where object graphs are created based off of a set of instructions to instantiate them. I think you are misinterpreting what the IServiceCollection is for. It does not store instances, it stores instructions on how to create instances. The instances aren't actually created until a constructor somewhere in the object graph requests one as a constructor parameter.
So, in short the reason why your service (which you call UserEndPointAccess) is not being instantiated when you request it is because you have not configured the IServiceCollection with instructions on how to create it.
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddApplicationInsightsTelemetry(Configuration);
services.Configure<Model.Meta.AppSettings>(Configuration.GetSection("AppSettings"));
services.AddSingleton(typeof(Logic.UserEndPointConfigurationHandler));
services.AddSingleton(typeof(Logic.NetworkHandler));
// Need a way to instantiate UserEndPointAccess via DI.
services.AddSingleton(typeof(DataAccess.UserEndPointAccess));
services.AddMvc();
}
So it seems like even I directly request to DI an Class with a Parameterless-Constructor, I need to register that.
If you are doing DI correctly, each service class will only have a single constructor. If you have more than one it is known as the bastard injection anti-pattern, which essentially means you are tightly coupling your class definition to other classes by adding references to them as foreign defaults.
And yes, you need to register every type you require (that is not part of MVC's default registration). It is like that in Unity as well.

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.

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.

how can i use structure map asp.net 3.5

I am new to the structure map but i want to use it in my asp.net site for dependency injection
can any one suggest me simple example to use structure map for the dependency injection
you will need to do something like this:-
StructureMapConfiguration
.ForRequestedType<IResourceA>()
.TheDefaultIsConcreteType<ResourceB>()
.CacheBy(InstanceScope.Singleton);
This tells StructureMap to inject ResourceB when there is a request for ResourceA.
Structure Map
You can configure programatically or via configuration file.
Programatical example (there are other ways):
StructureMap.StructureMapConfiguration.ForRequestedType<ISomething>().TheDefaultIsConcreteType<ConcreteSomething>();
then you can get an instance of the configured type using this sort of code:
//The concrete type will be ConcreteSomething
ISomething instance = ObjectFactory.GetInstance<ISomething>();
You can do it in a config file:
<StructureMap MementoStyle="Attribute">
<DefaultInstance PluginType="Blah.ISomething, Blah.SomethingDLL" PluggedType="Blah.Concrete.ConcreteSomething,Blah.ConcreteDLL"/>
</StructureMap>
and in the main method or Global.asax you can set this config by saying:
StructureMap.ObjectFactory.Initialize(x => { x.PullConfigurationFromAppConfig = true; });
and use it the same way as above:
ISomething instance = ObjectFactory.GetInstance<ISomething>();
If the concrete class has a constructor that needs instances injected in it, and you have those configured, the concrete types will get injected by the framework.
There are ways of passing parameters to constructors, dealing with Gereric types, creating named instances that are configured with specific constructor/property values. I use this framework and like it very much.

Resources