Due to limitations on the server side I need to build a self hosting web service in .NET...
I'm currently looking at HttpSelfHostServer but I'm very un-cool with it's magical construction of the controller, that seems to be, based on name alone and using only the default constructor.
For my tests I need to inject a value into the controller and using an IoC framework for this one usage where vanilla dependancy injection will suffice is over the top.
Is there any way I can do this with HttpSelfHostServer? or are there other, non-deprecated, self-hosting alternatives that give me control over my controller constructor calls.
The HttpSelfHostConfiguration instance that you need to provide to the HttpSelfHostServer constructor inherits the DependencyResolver property from the HttpConfiguration class. Hence, you can provide a custom dependency resolver as outlined here, for instance.
I was able to override IHttpControllerActivator in a unit test, I think it's similar to what you're trying to do.
e.g.
httpConfiguration.Services.Replace(typeof(IHttpControllerActivator),
Mock<IHttpControllerActivator>());
(there's more info. about services here)
Related
I have a WebApi that needs to add a singleton for DI during Setup. But I need to instantiate it during Startup. All of the example code I've found online shows something like this:
services.AddSingleton(new MyService());
This is great, but what do you do if MyService() takes arguments that are setup in DI? For instance, if my service's constructor is like this:
public MyService(ILogger<MyService> logger, IConfiguration config)
There must be a way to instantiate the object when adding it to the DI services, but I'm at a loss.
I'm using .NET 6.
Thanks
You basically have two options:
Create the object -with its dependencies- before or during the registration process. With ASP.NET Core the typical place to do this is inside the Startup.ConfigureServices method (or before).
Register it normally and resolve it directly after the container was constructed. In ASP.NET Core this typically means inside the Configure method.
In case the object needs to be available before registration (for instance because the registrations depend on the outcome of a method call on that object), it's important to keep that object as slim and with as little dependencies as possible. Such object, for instance, might have more functionality and dependencies than needs to execute at that moment. In that case it's good to split the object into smaller pieces, such that you only have to compose the least amount of dependencies to get the logic executed.
For instance, instead of injecting an IConfiguration, think about injecting just the parts of the configuration that the object requires. Also think about whether you require logging at this point. Especially logging is tricky, because it's tightly coupled into the DI infrastructure, which makes it more difficult to construct such class manually. This could hold for other framework dependencies as well, because most framework dependencies are registered in the built-in configuration system.
For application components, on the other hand, it should typically fairly easy to compose them before hand. You would usually see that the kinds of services you need this early in the process tend to have little dependencies -or- they can be refactored as such.
If that 'startup' service requires a deeper object graph resolving it from the DI container makes the most sense, but again, that requires the DI Container to be built. Only when executing the Configure method (or later) do you have access to the container.
What I would suggest is the have the following call in the startup:
builder.Services.AddSingleton<IMyService, MyService>(); Then the DI will instantiate any objects that are required in the MyService constructor.
Hope this helps.
I am trying to remove the Service Locator Anti Pattern that comes by default with a new MVC5 project. I am attempting to implement DI instead using Ninject. I have come upon the following guide which is meant for unity, not an MVC5 application.
http://tech.trailmax.info/2014/09/aspnet-identity-and-ioc-container-registration/
From what I can tell, there is not too much difference in code between that article and a new MVC5 application. However there is one thing that I cannot seem to figure out what to do with.
In the article I provided above exists the following method
private static void RegisterTypes(IUnityContainer container)
{
container.RegisterType<ApplicationDbContext>();
container.RegisterType<ApplicationSignInManager>();
container.RegisterType<ApplicationUserManager>();
}
I am trying to understand what this container is and what I would register my classes to in MVC5. Do I need to register my classes to some container to begin with? Still learning here and I'm quite new to MVC5 and Identity so any help is most appreciated.
The container contains configuration settings for each abstraction and its implementation. The container is used to create dependencies and inject them automatically when required. Whenever there is a need of instance of an abstraction, the container provides that to the requester. It automatically creates objects based on request and inject them when required. The container helps to manage dependencies with in the application in a simple and easy way.
I have a series of core services that I want to configure with Castle Windsor, things like Logging, Caching, Email config, etc. Making these services easily configurable by an app.config change would be a great boon (e.g. even just for development/testing it's great to be able to tell the app to route all the email traffic through some other mechanism than the actual mail server).
Two questions:
Many of the classes that need access to these services all inherit from an abstract base class (contains core logic used by all subclasses) so it would seem ideal to inject the core services into this base class somehow so that all the children would inherit the references to the services. Note these subclasses also all implement an Interface so that may be the better path to go down?
I also have a scenario where unrelated objects in other assemblies also need to be able to tap into the core services. These objects are not instantiated by me but by other libraries (I'm implementing the interface of some 3rd party library that then uses my implementation in its framework). If I need access to email or logging or some other core service in this code, how do I get a reference?
I hope that makes sense, thank you.
Regarding your first point, use property injection.
You have two choices for injecting dependencies; via the constructor or via properties. Since you don't want to pass dependencies down the constructor chain, the only other way is via property injection. This has the advantage that if a base class need to add/remove/change a dependency, it doesn't affect everything that inherits from it.
Some folks (myself included) shy away from property injection because it makes dependencies non-obvious and can imply that they are optional. This can make unit testing (you're doing that, right?) difficult because you have to inspect the class to see what dependencies are needed. If they were in the constructor, it'd be obvious.
However, if you can make sane null-object implementations of your services so that they are optional, or the unit-testing implications don't phase you, then this is a good route to go down.
As to your second question, if you can't control how the class gets created, you can't expect Windsor to supply any of its dependencies. At best, you can resolve the dependencies individually (i.e. call container.Resolve<IYourDependency>()) and assign them to the properties of your implementation.
So far in reading about possibilities of injection to custom membership providers, I've found two possible ways to do it:
One is the following: http://bugsquash.blogspot.com/2010/11/windsor-managed-membershipproviders.html
Here the author basically suggests to register your custom provider and then have a rather questionable windsor adapter for membership (I don't really like the way in which it instances your provider using a container it gets from HttpApplication, which it ultimately wraps with the windsor adapter).
This is another, similar option: http://code.google.com/p/webdotnet/source/browse/trunk/Steeg.Framework/Web/Security/MemberShipProvider.cs?r=2
Where you just override Initialize() and manually instance the dependencies there. At least in the first one, you don't need to instance dependencies by hand (other than the provider itself).
There are then a few which also suggest using a service locator of some kind (MVC's or otherwise)
Then I've come across ninject injecting dependencies to properties on Membership.Provider rather easily with something like _kernel.Inject(Membership.Provider). This is much closer to what I want, keeping the composition root concept which drew me to using DI in the first place.
How can I achieve a similar result using castle?
Update: apparently this has issues with lifecycle management.
Inject repository to custom membership provider with Ninject
Should I go for option #1 then? At least with that I instance the provider myself. So lifecycle management shouldn't be an issue.
I wouldn't go with implicit property injection, since the container will skip over the property if the type is not (correctly) registered, instead of failing fast (more info here). Instead I would use the Service Locator, but write a wrapper membership provider that does not contain any logic, but simply requests a membership provider from the service locator and calls that implementation. Jonas Gauffin wrote such a thing for MVC (using the DependencyResolver service locator), which is quite nice (also available on NuGet), but it is easy to do yourself.
Although the use of the service locator is considered an anti-pattern, please remember that the membership model must be configured through the web.config and this part of the system does not use the DependencyResolver.Current itself. Also writing such a DependencyResolverMembershipProvider is just a bit of mechanics and can be considered part of the composition root, not of the application. Calling the container inside your composition root is not a problem.
I have been trying to use Ninject today and have a couple of questions. First of all do I need to use the Inject attribute on all constructors that I want to use injection for. This seems like a really lame design? Do I need to create a Kernel then use that everywhere I pass in an injected class?
The best way to get started with Ninject is to start small. Look for a new.
Somewhere in the middle of your application, you're creating a class inside another class. That means you're creating a dependency. Dependency Injection is about passing in those dependencies, usually through the constructor, instead of embedding them.
Say you have a class like this, used to automatically create a specific type of note in Word. (This is similar to a project I've done at work recently.)
class NoteCreator
{
public NoteHost Create()
{
var docCreator = new WordDocumentCreator();
docCreator.CreateNewDocument();
[etc.]
WordDocumentCreator is a class that handles the specifics of creating a new document in Microsoft Word (create an instance of Word, etc.). My class, NoteCreator, depends on WordDocumentCreator to perform its work.
The trouble is, if someday we decide to move to a superior word processor, I have to go find all the places where WordDocumentCreator is instantiated and change them to instantiate WordPerfectDocumentCreator instead.
Now imagine that I change my class to look like this:
class NoteCreator
{
WordDocumentCreator docCreator;
public NoteCreator(WordDocumentCreator docCreator) // constructor injection
{
this.docCreator = docCreator;
}
public NoteHost Create()
{
docCreator.CreateNewDocument();
[etc.]
My code hasn't changed that much; all I've done within the Create method is remove the line with the new. But now I'm injecting my dependency. Let's make one more small change:
class NoteCreator
{
IDocumentCreator docCreator;
public NoteCreator(IDocumentCreator docCreator) // change to interface
{
this.docCreator = docCreator;
}
public NoteHost Create()
{
docCreator.CreateNewDocument();
[etc.]
Instead of passing in a concrete WordDocumentCreator, I've extracted an IDocumentCreator interface with a CreateNewDocument method. Now I can pass in any class that implements that interface, and all NoteCreator has to do is call the method it knows about.
Now the tricky part. I should now have a compile error in my app, because somewhere I was creating NoteCreator with a parameterless constructor that no longer exists. Now I need to pull out that dependency as well. In other words, I go through the same process as above, but now I'm applying it to the class that creates a new NoteCreator. When you start extracting dependencies, you'll find that they tend to "bubble up" to the root of your application, which is the only place where you should have a reference to your DI container (e.g. Ninject).
The other thing I need to do is configure Ninject. The essential piece is a class that looks like this:
class MyAppModule : NinjectModule
{
public override void Load()
{
Bind<IDocumentCreator>()
.To<WordDocumentCreator>();
This tells Ninject that when I attempt to create a class that, somewhere down the line, requires an IDocumentCreator, it should create a WordDocumentCreator and use that. The process Ninject goes through looks something like this:
Create the application's MainWindow. Its constructor requires a NoteCreator.
OK, so create a NoteCreator. But its constructor requires an IDocumentCreator.
My configuration says that for an IDocumentCreator, I should use WordDocumentCreator. So create a WordDocumentCreator.
Now I can pass the WordDocumentCreator to the NoteCreator.
And now I can pass that NoteCreator to the MainWindow.
The beauty of this system is threefold.
First, if you fail to configure something, you'll know right away, because your objects are created as soon as your application is run. Ninject will give you a helpful error message saying that your IDocumentCreator (for instance) can't be resolved.
Second, if management later mandates the user of a superior word processor, all you have to do is
Write a WordPerfectDocumentCreator that implements IDocumentCreator.
Change MyAppModule above, binding IDocumentCreator to WordPerfectDocumentCreator instead.
Third, if I want to test my NoteCreator, I don't have to pass in a real WordDocumentCreator (or whatever I'm using). I can pass in a fake one. That way I can write a test that assumes my IDocumentCreator works correctly, and only tests the moving parts in NoteCreator itself. My fake IDocumentCreator will do nothing but return the correct response, and my test will make sure that NoteCreator does the right thing.
For more information about how to structure your applications this way, have a look at Mark Seemann's recent book, Dependency Injection in .NET. Unfortunately, it doesn't cover Ninject, but it does cover a number of other DI frameworks, and it talks about how to structure your application in the way I've described above.
Also have a look at Working Effectively With Legacy Code, by Michael Feathers. He talks about the testing side of the above: how to break out interfaces and pass in fakes for the purpose of isolating behavior and getting it under test.
First of all do I need to use the Inject attribute on all constructors
that I want to use injection for. This seems like a really lame
design?
No you shouldn't have to do this at all actually. Since you work with ASP.NET MVC you can just install the Ninject.MVC3 Nuget package. This will get you started with a NinjectMVC3 class in the App_Start folder. You can use the RegisterServices method to register your interfaces/classes with Ninject. All controllers that have dependencies to those interfaces will then be automatically resolved by Ninject, there is no need for the Inject attribute.
Do I need to create a Kernel then use that everywhere I pass in an
injected class?
No - what you are describing sounds more like the Service Locator pattern, not dependency injection - you will want to pass in your dependencies ideally in the constructor, instead of resolving them within particular classes using the kernel. There should be just one central composition root where the resolving is done, which is within the composition root in either the RegisterServices method mentioned above or a separate Ninject module instantiated there - the later approach will allow you a little more flexibility and modularity (no pun intended) in changing how you resolve your dependencies.
Here's a good beginner's tutorial on dependency injection with Ninject and MVC3.
Don't forget there are docs, including an intro I feel would be very appropriate given the sort of questions you are asking on the Ninject Wiki. You're just annoying yourself if you're trying to use Ninject without reading it end to end.
Stick the table of contents on your bookmark bar for a bit.
I can also highly recommend Mark Seemann's Dependency Injection in .Net as a companion book for DI based architecture (even though it doesnt directly cover Ninject).