I am trying to learn about dependency injection and i'm using the unity application block to help.
What I want to do is, have a console app that will register a class (as long as it implements a specific interface) and execute a method...
So the method on the class that implements the method will be executed.
Hope that makes sense...a nice nudge in the right direction would be perfect!
I'm looking at the docs on msdn, but i'm still not 100% sure of how to go about it.
Thx
Steve
var container = new UnityContainer();
container.RegisterType<IFoo, Foo>();
container.Resolve<IFoo>().Bar();
When Resolve is called, it will return an instance of Foo since that was what was registered for the IFoo interface.
Unity does not have convention-based registration features like more advance DI Containers. If you want late-bound composition, you may want to take a look at MEF instead.
I've never heard of the MEF but all you need to do is implement a simple plugin pattern. I wrote an article a while back on how to do this for a database engine but it can easilly be applied to anything that implements an interface:
http://www.simonrhart.com/2009/04/example-of-plugin-pattern-on-compact.html
Related
I am trying to incorporate Microsoft.Extensions.DependencyInjection into an existing ASP.NET 4.6.1 app.
I know that while .NET Core has it built-in, for 4.6.1 you need to create some initial classes as outlined in http://scottdorman.github.io/2016/03/17/integrating-asp.net-core-dependency-injection-in-mvc-4/. (The article seems to be out of date since the sample code does not show implementation of BeginScope() and Dispose() for IDependencyResolver. If anybody has more updated examples that would be appreciated.)
"Services" accessed by controllers where you are creating instances via constructors is fairly simple but my problem is when I need an instance of "something" that is from a property or method of an existing object.
For example, I have a inherited DbContext that needs an instance of System.Security.Principal.IIdentity that comes from the logged in user.
Another example is an instance of ApplicationUser. ApplicationUser inherits IdentityUser and the current user can be found by calling FindById() method of AppUserManager.
While AppUserManager can easily be instantiated using DI, how can I use DI the inject the output of the FindById() method? I cannot seem to find any documentation or sample code about this for Microsoft based framework. Other frameworks like Unity seem to support Property-based injection.
In essence, can DI be used with all existing classes or do you specifically need to code out the classes to support DI from the beginning? (i.e. only expect parameters to be passed in via constructors and make sure those instances themselves are created via constructors).
The very simple and short answer to your question "Does Microsoft DependencyInjection support non-constructor injection?" is, no.
Out-the-box Microsoft DI does not currently support property injection like other frameworks such as Ninject. If you need that feature, I suggest using those frameworks instead (I cant imagine MS has any plans to add property injection any time soon).
Your other option is to consider how you can refactor your code to use constructor injection instead which is the preferred method
This may be a silly question, so sorry for asking this, and fyi I'm new to this kind of stuff.
After reading the documentation about mirrors, I can only grasp that the mirrors API is just like copying some instance plus access to some method that I don't know when/why to use.
Anybody care to give me some pointers, some example would be nice.
Mirror API allows you to retrieve metadata about objects and types programmatically (during execution) and to execute methods on objects . It is similar to reflection in .NET or Java.
A typical example is implementing plugin support:
Let's say that you define an IPlugin interface and want to automatically register with your PluginManager an instance of each type that implements it, without need to explicitly register each new implementation. Sometimes you even don't know all the plugins in advance, e.g. if users can deploy their own plugins.
You could do it like this (WARNING: I have never used Mirror API, so this is a high level description based on API documentation, not a proper implementation):
You first use MirrorSystem.libraries to get LibraryMirror instance for each library in that MirrorSystem
Then for each LibraryMirror you use classes property to get ClassMirror for each class in the library
For each ClassMirror use superinterfaces to get all implemented interfaces
If any of the implemented interfaces is IPlugin you can create an instance of that class (ClassMirror.newInstance) and register it with plugin manager.
Without mirror API, you would not be able to enumerate all the types, find what interfaces they implement (without creating an object) or create an instance of a type that you don't know about in advance.
To be honest I am not sure what is the current state of mirror API in Dart, I believe that it is still not finished, but I might be wrong.
I've started a new project and have been gradually building my service layer up using ninject and the unit of work pattern. I've come across a problem and am looking for some help.
I have a LicenceService that requires access to the UserService so the constructor is
public LicenceService(IRepository<Licence> licenceRepo, IUserService userService)
however I'm now in the situation where my UserService needs access to the LicenceService so the constructor would be
public UserService(IRepository<User> userRepo, ILicenceService licenceService)
I'm guessing by this point you can see my circular reference problem. As Imagine this is not an uncommon problem does anybody have any suitable solutions.
How about a third service to hold references to both and communicate between them?
That is to say that the third service would call both, for specific purposes, rather than one having to know about the other.
You can solve this with a factory or delegate, but really it's a design issue. See if you can factor out some code into a third class to remove the circular dependencies.
Im new to IOC and StructureMap and have an n-level application and am looking at how to setup the wirings (ForRequestedType ...) and just want to check with people with more experience that this is the best way of doing it!
I dont want my UI application object to reference my persistence layer directly so am not able to wire everything up in this UI project.
I now have it working by defining a Registry class in each project which wires up the types in the project as needed. The layer above registers its types and also calls the assembly below and looks for registries so that all types are registered throught the hierrachy.
E.g. I have UI, Service, Domain, and Persistence libraries. In my service layer the registry looks like
Scan(x =>
{
x.Assembly("MyPersistenceProject");
x.LookForRegistries();
});
ForRequestedType<IService>().TheDefault.Is.OfConcreteType<MyService>();
Is this a recommended way of doing this in a setup such as this? Are there better ways and what are the advantages / disadvantages of these approaches in this case?
This sounds good.
If you use default conventions, like having a default implementation OrderSevice for the interface IOrderService you can reduce the wiring by using conventions in StructureMap. The WithDefaultConventions is a method in the Registry to use default conventions. You can also specify your own convention and register it in the registry using the method With, see the StructureMap documentation
I'm playing around with some Dependency Injection (StructureMap) with my ASP.NET MVC application. Works great.
Becuase StructureMap is using DI via the most gready constructor (I hope I got that concept named right), I'm under the impression that it creates an instance of an object for each argument, in the most gready constructor.
So, is it possible to tell a DI framework (in this case, it's StructureMap but i'm curious if it can do it for any other .NET DI Framework) to NOT create the instance when the constructor is called, but to delay that object's construction until required?
Sorta like some lazy-object construction or something...
All di frameworks that support singleton->session/request scoped mappings typically instantiate a proxy object instead of the "real" object when a singleton object needs to access a session scoped object. Construction of the "real" instance is normally deferred to the first time a method on the proxy is invoked.
I believe castle windsor supports this mechanism.
Short answer: Yes, you can do this. Register your types using the .Net 4 Lazy<T> class like this:
x.For(typeof(Lazy<>)).Use(typeof(Lazy<>))
.CtorDependency<bool>("isThreadSafe").Is(true);
For the long answer and explanation, see my answer to question 6811956. I think it will give you what you need. If you aren't using .Net 4 you'll have to implement your own Lazy<T> class to pull this off. See question 3207580 as a starting point.
Does Structuremap support Lazy out of the box?
Implementation of Lazy<T> for .NET 3.5
UPDATE: In StructureMap 3, "CtorDependency" has become just "Ctor", but otherwise seems to be working just the same.