Ninject binding/unbind issue - asp.net-mvc

I have a bit of a dilemma, which to be honest is a fringe case but still poses an issue.
Currently I am using Ninject MVC and bind all my controllers like so:
Kernel.Bind<SomeController>.ToSelf();
Which works a treat for 99% of things that I have needed to do, however at the moment I am doing some wacky stuff around dynamic routing and dynamic controllers which require me to manually write a method to get the type of a controller from ninject. Now initially I thought it would be easy, but its not... I was expecting that I could get the controller based on its name, but that didnt work.
Kernel.Get<IController>("SomeController");
That got me thinking that its probably because it only knows about a binding to SomeController, not IController. So I thought, I can just write all my bindings like so:
Kernel.Bind<IController>.To<SomeController>().Named("SomeController");
This way it should be easy to get the type of the controller from the name doing the previous code, however if I were to bind this way, I would have a problem when I come to unbind the controllers (as plugins can be loaded and unloaded at runtime). So the normal:
Kernel.Unbind<SomeController>()
Which was great, will no longer work, and I would have to do:
Kernel.Unbind<IController>();
However then I realised that I need to give it some constraint to tell it which binding for this type I want to unbind, and there seems to be no overloads or DSL available to do this...
So I am trapped between a rock and a hard place, as I need to satisfy the ControllerLookup method, but also need to keep it so I can add and remove bindings easily at runtime.
protected override Type GetControllerType(RequestContext requestContext, string controllerName) {
//... find and return type from ninject
}
Anyone have any ideas?
(Just incase anyone questions why I am doing this, its because of the way I am loading plugins, Ninject knows about the types and the namespaces, but within the context of creating a controller it doesn't know the namespace just the controller name, so I do this to satisfy the isolation of the plugin, and the location of the dynamic controller, it is a roundabout way of doing it, but it is what people have done with AutoFac before Example of similar thing with AutoFac)

In my opinion the bindings should be created once at application startup and not change anymore after the first resolve. Everything else can lead to strange issues. Unless you have proper isolation using an AppDomain for each plugin you can not really unload them anyway. Instead of unloading bindings you can make them conditional and disable them using some configuration.
If you really want to unload bindings then I suggest not to do it for single bindings but take advantage of modules. Load all bindings belonging to one plugin together in one or several modules and unload those modules instead of the single bindings.

Related

Getting Injectee from Jersey vs HK2

Short story: I want to get the Injectee from within a Supplier that is bound using Jersey's AbstractBinder.bindFactory(Class) method.
Basically to work around JERSEY-3675
Long story: I was using the org.glassfish.hk2.api.Factory method to create an instance of my RequestScoped Object and life was good.
I moved my registration into a Feature and then life was not good because of JERSEY-3675.
Long story short, org.glassfish.hk2.utilities.binding.AbstractBinder do not work inside Features. No problem, I thought, I will use org.glassfish.jersey.internal.inject.AbstractBinder.
Slight problem I encountered: Jersey's AbstractBinder.bindFactory() method takes in Supplier not Factory. No problem, I thought, I will use Supplier (I like it better, anyway).
Bigger problem I encountered: I had been using org.glassfish.hk2.api.Injectee to get the InstantiationData about who was calling the injection. This does not get injected if I do not use HK2's Factory. The javadoc even says the method is 'indeterminate' if not called from Factory.provide().
Even though there is a Jersey Injectee (org.glassfish.jersey.internal.inject.Injectee), this seems to only be available when using Jersey's InjectionResolver. I do not want to use InjectionResolver because
HK2's InjectionResolver must be Singleton but I want to have RequestScoped stuff in my injected object.
On second read, though, Jersey's InjectionResolver does not say anything about needing to be Singleton. Can anyone confirm?
I do not want to create my own annotation for this (I have created my own annotations and InjectionResolvers for other cases)
I do not feel confident overriding #Inject with an InjectionResolver. Not sure what that means or how I would be able to register multiple of those and have them work together (one for each Feature)
In meantime, I am using the workaround mentioned in the bug.
I am new to DI scene, so if something (or all of it) does not make sense, please let me know.

Guice override some bindings in an existing injector

I have an Injector instance a, and I'd like to create another Injector b which does the same as a, except for two bindings, which get overridden by the Module I provide. Is this possible?
I know about Modules.override, but that does not take an Injector as argument. If it was possible to convert an Injector to a Module, that would solve my problem.
The simplest way of thinking about this would be through child injectors, but that is explicitly disallowed as a design decision:
The reason overriding a binding in a child injector isn't supported is because it can lead a developer towards writing code that can work in either a parent & child injector, but have different behavior in each. This can lead to very surprising scenarios, because of just-in-time (JIT) bindings and the way they interact with parent/child injectors.
At this point, I would probably think about restructuring your application to avoid requiring these complicated bindings, but if you want to go further, you can probably use Injector.getBindings() or Injector.getAllBindings() (note the difference!) and stitch them back into a module using the Elements SPI. After all, Binding<?> extends Element, and Elements.getModule(...) will create a Module from your Elements. I haven't checked that it works, but that's probably your best lead.

Is there a Django's context processor like in Grails?

I want to output a value which is global in all the templates or even layout in Grails, like Django's context processor where you could render the context and use it as global variable in the templates.
Is there a concept like this in Grails? And, how can I use that in the layout?
I am not familiar with Django at all. Looked up Django's context processor in google, I think I get it. Basically it configures reusable data that gets injected into every template? Anyway, as far as I know nothing like that exists in Grails. You can try the following as a workaround.
Use ApplicationContext
Every view has access to the applicationContext. So make a service that holds all the data you need, let's say it is called fooService, and the data item you want is a field in the service called bar (could be a method too of course). Then in your view do ${applicationContext.fooService.bar}. Resource for accessing applicationContext in view: http://mrhaki.blogspot.com/2011/11/grails-goodness-get-grailsapplication.html.
Use your layout
I am not sure about this one, so use at your own risk. The top one is of course extremely verbose. It would be annoying to call that over and over again in different views. So instead, call it once and make it a variable in your layout with g:set. I think the variable will be available in every view that uses that layout.... but not sure. Here are the docs for g:set -> http://grails.org/doc/latest/ref/Tags/set.html.
If I didn't get what context processors do in python I am happy to try again...

Repository Pattern in asp.net mvc with linq to sql

I have been reading though the code of the NerdDinner app and specifically the Repository Pattern...
I have one simple question though, regarding this block
public DinnersController()
: this(new DinnerRepository()) {
}
public DinnersController(IDinnerRepository repository) {
dinnerRepository = repository;
}
What if each Dinner also had, say, a Category... my question is
Would you also initialize the category Repository in the constructor of the class??
Im sure it would work but Im not sure if the correct way would be to initialize the repository inside the method that is going to use that repository or just in the constructor of the class??
I would appreciate some insight on this issue
Thanks.
What you're looking at here is actually not so much to do with the repository pattern, per se, and more to do with "dependency injection," where the outside things on which this class depends are "injected" from without, rather rather than instantiated within (by calling new Repository(), for example).
This specific example shows "constructor injection," where the dependencies are injected when the object is created. This is handy because you can always know that the object is in a particular state (that it has a repository implementation). You could just as easily use property injection, where you provide a public setter for assigning the repository or other dependency. This forfeits the stated advantage of constructor injection, and is somewhat less clear when examining the code, but an inversion-of-control container can handle the work of instantiating objects and injecting dependencies in the constructor and/or properties.
This fosters proper encapsulation and improves testability substantially.
The fact that you aren't instantiating collaborators within the class is what improves testability (you can isolate the behaviour of a class by injecting stub or mock instances when testing).
The key word here when it comes to the repository pattern is encapsulation. The repository pattern takes all that data access stuff and hides it from the classes consuming the repository. Even though an ORM might be hiding all the actual CRUD work, you're still bound to the ORM implementation. The repository can act as a facade or adapter -- offering an abstract interface for accessing objects.
So, when you take these concepts together, you have a controller class that does not handle data access itself and does not instantiate a repository to handle it. Rather the controller accepts an injected repository, and knows only the interface. What is the benefit? That you can change your data access entirely and never ever touch the controller.
Getting further to your question, the repository is a dependency, and it is being provided in the constructor for the reasons outlined above. If you have a further dependency on a CategoryRepository, then yes, by all means inject that in the constructor as well.
Alternatively, you can provide factory classes as dependencies -- again classes that implement some factory interface, but instead of the dependency itself, this is a class that knows how to create the dependency. Maybe you want a different IDinnerRepository for different situations. The factory could accept a parameter and return an implementation according to some logic, and since it will always be an IDinnerRepository, the controller needs be none the wiser about what that repository is actually doing.
To keep your code decoupled and your controllers easily testable you need to stick with dependency injection so either:
public DinnersController()
: this(new DinnerRepository(), new CategoryRepository()) {
}
or the less elegant
public DinnersController()
: this(new DinnerRepository(new CategoryRepository())) {
}
I would have my dinner categories in my dinner repository personally. But if they had to be seperate the id put them both in the ctor.
You'd want to pass it in to the constructor. That said, I probably wouldn't create any concrete class like it's being done there.
I'm not familiar with the NerdDinner app, but I think the preferred approach is to define an IDinnerRepository (and ICategoryRepository). If you code against interfaces and wanted to switch to say, an xml file, MySQL database or a web service you would not need to change your controller code.
Pushing this out just a little further, you can look at IoC containers like ninject. The gist of it is is that you map your IDinnerRepository to a concrete implementation application wide. Then whenever a controller is created, the concrete repository (or any other dependency you might need) is provided for you even though you're coding against an interface.
It depends on whether you will be testing your Controllers (, which you should be doing). Passing the repositories in by the constructor, and having them automatically injected by your IOC container, is combining convenience with straightforward testing. I would suggest putting all needed repositories in the constructor.
If you seem to have a lot of different repositories in your constructors, it might be a sign that your controller is trying to do too many unrelated things. Might; sometimes using multiple repositories is legitimate.
Edit in response to comment:
A lot of repositories in one controller constructor might be considered a bad code smell, but a bad smell is not something wrong; it is something to look at because there might be something wrong. If you determine that having these activities handled in the same controller makes for the highest overall simplicity in your solution, then do that, with as many repositories as you need in the constructor.
I can use myself as an example as to why many repositories in a controller is a bad smell. I tend to get too cute, trying to do too many things on a page or controller. I always get suspicious when I see myself putting a lot of repositories in the constructor, because I sometimes do try to cram too much into a controller. That doesn't mean it's necessarily bad. Or, maybe the code smell does indicate a deeper problem, but it not one that is too horrible, you can fix it right now, and maybe you won't ever fix it: not the end of the world.
Note: It can help minimize repositories when you have one repository per Aggregate root, rather than per Entity class.

Can Autofac do automatic self-binding?

I know some DI frameworks support this (e.g. Ninject), but I specifically want to know if it's possible with Autofac.
I want to be able to ask an Autofac container for a concrete class, and get back an instance with all appropriate constructor dependencies injected, without ever registering that concrete class. I.e., if I never bind it explicitly, then automatically bind the concrete class to itself, as if I had called builder.Register<MyClass>();
A good example of when this would be useful is ViewModels. In MVVM, the layering is such that only the View depends on the ViewModel, and that via loose typing, and you don't unit-test the View anyway. So there's no need to mock the ViewModel for tests -- and therefore there's no reason to have an interface for each ViewModel. So in this case, the usual DI pattern of "register this interface to resolve to this class" is unnecessary complexity. Explicit self-binding, like builder.Register<MyClass>();, also feels like an unnecessary step when dealing with something as straightforward as a concrete class.
I'm aware of the reflection-based registration example in the Autofac docs, but that's not to my taste either. I don't want the complexity (and slowness) of registering every possible class ahead of time; I want the framework to give me what I need when I need it. Convention over configuration, and all that.
Is there any way to configure Autofac so it can say "Oh, this is a concrete type, and nobody registered it yet, so I'll just act like it had been registered with default settings"?
builder.RegisterTypesMatching(type => type.IsClass)
If you look at the source you will see that RegisterTypesMatching (and RegisterTypesFromAssembly) is NOT DOING ANY REFLECTION. All Autofac is doing in this case is registering a rule that accepts a type or not. In my example above I accept any type that is a class.
In the case of RegisterTypesFromAssembly, Autofac registers a rule that says "if the type you're trying to resolve have Assembly == the specified assembly, then I will give you an instance".
So:
no type reflection is done at register time
any type that matches the criteria will be resolved
Compared to register the concrete types directly, this will have a perf hit at resolve time since Autofac will have to figure out e.g. constructor requirements. That said, if you go with default instance scope, which is singleton, you take the hit only the first time you resolve that type. Next time it will use the already created singleton instance.
Update: in Autofac 2 there is a better way of making the container able to resolve anything. This involves the AnyConcreteTypeNotAlreadyRegistered registration source.
what about:
builder.RegisterTypesFromAssembly(Assembly.GetExecutingAssembly());
no reflection is done, as Peter Lillevold points out.

Resources