Ninject: Choosing the wrong constructor - asp.net-mvc-3

I have an ASP.NET MVC 3 application with Ninject v2.2.1.4. Everything was working great and then suddenly we started seeing Ninject attempting to create our DbContext using a constructor with a parameter over the parameterless constructor. Here are the bindings:
kernel.Bind<MyContext>().ToSelf().InRequestScope();
kernel.Bind<IUnitOfWork>().ToMethod(ctx => ctx.Kernel.Get<MyContext>());
kernel.Bind<DbContext>().ToMethod(ctx => ctx.Kernel.Get<MyContext>());
The MyContext is a DbContext object that implements the IUnitOfWork interface as well. I have set it up this way so the same context is injected into multiple repositories that are used in a single request. The MyContext constructors look like this:
public MyContext() { }
public MyContext(string connectionString) { }
public MyContext (long accountID) { }
public MyContext (Connection connection) { }
There are different constructors for different applications as they all use the same MyContext class. Looking at the bindings you would think when a MyContext class was requested that the parameterless constructor would be called but for whatever reason, it is not. The one with the long accountID parameter is called even though no accountID is being specified. This obviously throwns and exception statement that "No matching bindings are available, and the type is not self-bindable" It actually throws the exception when trying to generate a IUnitOfWork.
If I comment out the last three constructors everything works fine and the parameterless constructor is used. If I comment out any two of the parameterized constructors it tries to use the other and not the parameterless one.
The suggestions provided by Ninject are:
Suggestions:
1) Ensure that you have defined a binding for long.
2) If the binding was defined in a module, ensure that the module has been loaded into the kernel.
3) Ensure you have not accidentally created more than one kernel.
4) If you are using constructor arguments, ensure that the parameter name matches the constructors parameter name.
5) If you are using automatic module loading, ensure the search path and filters are correct.
We don't have anything for 1 as we don't want to. I'm not sure what 2 and 5 mean. I do not believe we have done 3 and we are not doing 4.
Any thoughts as to why it wouldn't use the parameterless constructor in this scenario.

#Xander's answer is right in general but Ninject has some very specific solutions in V3.
Ninject scores constructors by a specific algorithm which is to find the one with the most parameters it knows how to resolve as documented in this wiki article [which claims to be for V2.4, which was actually badged 3.0]. See the code. I think this is also on the wiki. If it's not, someone should put it there.
RE the change in behavior you've seen, the chances are either Implicit Self Binding is changing the goalposts (new registrations are being added during resolution) or you've added a Binding that has made one of the other constructors more attractive.
The [Inject] attribute trumps all other criteria which is what you're after (although you don't actually want to have container specific attributes in your code).
The WithConstructorArgument technique suggested is actually effected by using ToConstructor - doing a WCA will not influence the selection (and I reckon you won't get complaints about the redundant specifications.
The real bottom line is that you should never end up in as big a mess as this as alluded to in #Mark Seemann's comment on this related question.
Sadly, the above is all a lie. If you move off v2.2, this answer will become correct. If you can't or won't, you need to look at the equivalent source and tests to find out the rules from before that (from memory (and some google code that appeared in search results in my research), it was based on the constructor count, but not sure how equal scores are disambiguated.
Pretty sure that in 2.2, adding an [Inject] is the quick way out.

By default Ninject, along with other similar IoC frameworks, chooses the constructor with the most parameters. Specify which constructor to use during the initialization by the WithConstructorArgument extension method.
kernel.Bind<DbContext>()
.WithConstructorArgument("connectionString",
ConfigurationManager.ConnectionStrings["connection"]
.ConnectionString)
.ToMethod(ctx => ctx.Kernel.Get<MyContext>());
To force Ninject to use the default constructor place the [Inject] attribute on the constructor:
[Inject]
public MyContext() { }

Related

Best approach for Dependency Injection in Laravel 5 package

I am developing a package for Laravel 5, and now I need to benefit from dependency injection to have a more scalable and relaible application, I don't know which approach is the best to take and why, this is a piece of my code and I need to injected the Lang class dependency
class MyController extends \App\Http\Controllers\Controller
{
public $text;
public $lang;
public function __construct()
{
// Some codes here
}
public function myFunction(){
$this->text = \Lang::get('package::all.text1');
}
}
In this link http://laravel.com/docs/4.2/ioc 2 approaches are suggested, Basic Usage and Automatic Resolution based on my understanding from the link
taking the first approach I need to add
App::bind('lang', function($app)
{
return new \Lang();
});
to the register part of application and then in the function I'll have something
like this :
public function myFunction()
{
$lang = \App::make('lang');
$this->text = $lang::get('package::all.text1');
}
The other way is to modify the constructor like
public function __construct(Lang $lang)
{
$this->lang = $lang;
}
And then instantiate object from Class like
$myController = App::make('MyController');
Which way is the better way to take for, considering that this class is a Controller and it will be called in the routes file, or please correct me if my understanding from the link is not right. please also inform me why you suggest any of those approaches.
It should be noted that using local IoC resolution ($app->make() stylee) is not much better than using the facades directly (Lang::get() stylee) - you're still very much relying on Laravel's specific classes without really making your code explicitly state that it needs these exact classes. So the general advice is to, as much as possible, code to an interface if you want your code to be as portable as possible.
Of course there are a couple of big downsides to this currently in PHP development:
These interfaces are not generally defined (except the PSR-3 LoggerInterface interface) so you still have to rely on a particular instance of the interface (in this case, Laravel's).
If you decide to make your own generic interface (or the FIG eventually creates some of these), the classes that Laravel provides for translation (for example) don't implement it anyway, so you then need to subclass the existing ones just to make it look like it implements your own interface. But hey, that's the current best practice, so I guess if you wanna be using the current best practices, code to an interface, and don't worry for the time being that the interface you're coding to is Laravel-specific.
But anyway, here are my thoughts on your specific question. First off I should say that I haven't actually used Laravel 5 yet (just the 4s), but I have generally followed its development.
If the class I am coding will use a given dependency quite a lot or as a core part of how the class works I will use constructor dependency injection. Examples here are the Request or some Repository class in a controller, or a business logic class in a console command class.
If what I need I only need for a specific purpose (maybe redirecting from a controller and needing to generate a URI) I will resolve a local version from the IoC container ($this->app->make()) and then use that. If I were using Laravel 5 and the method was called by Laravel directly (e.g. a controller's action method) I may use method injection for this, I'm not 100% sure.
As a final note, the general advice is that if your constructor method signatures get too big due to a lot of dependencies:
It's time to have a look at if your code relies too much on external dependencies. Maybe some of the functionality of your class can be extracted to its own class that splits the dependencies between the two.
You should consider using setter methods rather than constructor injection - so instead of accepting a Request object, you have a $class->setRequest() method. The downside of doing this is that you need to tell Laravel's IoC container how to instantiate your object (i.e. that these setters must be called). It's not that big a deal but something worth noting.
Relevant links:
Laravel 5's IoC article
Laravel 5's Controller injection advice

Can anyone explain the purpose and resolution of CA1822 on a Controller Action?

Error CA1822 : Microsoft.Performance : The 'this' parameter (or 'Me'
in Visual Basic) of 'SomeController.AnAction(string, string)' is never
used. Mark the member as static (or Shared in Visual Basic) or use
'this'/'Me' in the method body or at least one property accessor, if
appropriate.
A static action yields 404 not found when requested via URL. The action is working as expected with code analysis turned off. What's the point of this and what's the appropriate remedy?
Note that the return type of the action is PartialViewResult, it doesn't seem as though code analysis complains about this if the return type is ActionResult.
[HttpPost]
public PartialViewResult BlankEditorRow(string formId, Common.Entities.Common.ObjTypeEnum objType)
{
if (objType == Common.Entities.Common.ObjTypeEnum.Regular)
return new AjaxPartialViewResult("_RowEditor", new ProcedureEntryEntity()) { UpdateValidationForFormId = formId };
else
return new AjaxPartialViewResult("_TemplateRowEditor", new ProcedureEntryEntity()) { UpdateValidationForFormId = formId };
}
Update: Looks like changing the return type to ActionResult resolves the error, and PartialViewResult is an ActionResult so it should work.
I doubt that changing the return type without calling using any instance members really resolves the problem. I suspect that in order to change the return type, you changed the return statement to something which accessed an instance member.
Now I don't know whether the route handling in MVC will let you mark the method as static, but it's worth investigating. Even though the warning is given in terms of performance, I would think of it in terms of intent and readability.
Typically there are two reasons for a method or property to be an instance member (rather than static):
It needs to access another instance member, because the way it behaves depends on the state of the object
It needs to behave polymorphically based on the actual type of the instance it's called on, so that the behaviour can be overridden
If neither of these is the case, then the method can be made static which indicates that there's no polymorphism expected and no instance state required. A static member effectively advertises that the only state it depends upon is the state of the type itself (and the parameters), and that it won't behave polymorphically. Aside from anything else, that means you can test it without creating an instance at all, too.
Of course, if MVC's infrastructure requires it to be an instance method, then you should just suppress the warning, with a comment to indicate that fact.
I think CA just does not take into account that this is a controller action in MVC app. I would suppress.

Registering all types in Assembly for Unity

I'm working on a large Asp.Net MVC3 application (>50 views) and we are currently planning on using Unity for our dependency injection framework. For ease of maintenance, I would like to be able to query the assembly to find all of the base types, then register them with Unity.
Based on sample code from the Unity MVC3 Project for registering all controllers, I tried the following code -
var orchestratorTypes = (from t in Assembly.GetCallingAssembly().GetTypes()
where typeof(IOrchesratorBase).IsAssignableFrom(t) &&
!t.IsAbstract
select t).ToList();
orchestratorTypes.ForEach(t => container.RegisterType(t);
When I run the application I get the following error message
The current type, WwpMvcHelpers.BaseClasses.IOrchesratorBase, is an interface and cannot be constructed. Are you missing a type mapping?
If I register the class using individually, as below -
container.RegisterType<IOrchesratorBase, HomeOrchestrator>();
Everything works correctly. Is there a way to do this so that I don't have to register each type individually?
EDIT
Per request, my inheritance hierarchy is
HomeOrcestrator <- IOrchesratorBaseList<LocalModel>
<- OrchesratorBase<LocalModel> <- IOrchesratorBase
The usage in the controller is
public class HomeController : ControllerListBase <HomeOrchestrator, LocalModel>
{
public HomeController() {}
public HomeController(IOrchesratorBase homeOrchestrator) {
this.Orchestrator = (HomeOrchestrator) homeOrchestrator;
}
The LINQ to get the types appears to work. I don't think that's your problem.
You'll get a similar error if you just write
container.RegisterType(typeof(HomeOrchestrator));
and call container.Resolve<IOrchesratorBase>().
In other words, RegisterType(t) is not the same as RegisterType<I, T>().
The real question is, what are you resolving and how do you want it resolved? Your query is finding implementors of IOrchesratorBase. Are your injection constructor parameters of that type? If so, what's Unity supposed to do when 20 types implement that interface?
Can you provide more information on your class/interface hierarchy, constructor parameters, and what you expect/want to happen?
(I'd refactor to change IOrchesratorBase to IOrchestratorBase, BTW.) :)
Edit
Based on the edited question, the problem is that, in order to resolve a HomeController, Unity is looking for a type registration for IOrchesratorBase. It determines the interface type by the parameter types of the constructor with the most parameters.
If you write container.RegisterType<IOrchesratorBase, HomeOrchestrator>() the answer is obvious - Unity will construct an instance of HomeOrchestrator and inject it.
Now, is there more than one type that implements IOrchesratorBase? If so, and you register both of them (explicitly), Unity will use whichever one you register last. That may not be what you want.
If you have multiple controllers, each taking a different interface type in their constructors (with only one implementation per interface), you'll need to figure out what each interface type is and re-run your LINQ registration for each one. That could be done via reflection - find the orchestrators or the controllers.
If you have multiple controllers, each taking the same interface type in their constructors and you want different implementations for each, you've got a problem. You'd have to register named types and determine the names somehow, or something similar.
Unity isn't magic. It can't figure out your intentions.
Addendum
Unity can operate in a convention-over-configuration mode; see Using Unity With Minimal Configuration.

business methods in playframework contolles

Could somebody explain is it possible to have potected, pivate methods in playfamewok's contolles except:
public static void method-action-name() {}
For example if I would have method like this:
protected static int doSomeWork() {}
and this method would be invoked in method-action-name() ..
public static void method-action-name() {
...
int resul = doSomeWork();
...
}
I do not want to have long action-method, so I would like to split it to smaller ones, and then reuse it in other action-methods.
I mean is it ok (from playframework's point of view) to have such method in controller side instead of having them in domain classes? In Spring Framework, we use BP (business process) beans for that, for example.
Is it ok to have such helper methods for business methods in playframework controllers ?
Added after having answer & comments:
For example if I have SearchController class then for that class would be nice to have methods like preSearch1(), preSearch2() what search() method would use, but if I move these methods (1,2) to another class then it should be class with name like SearchHelper then? in package named /src/helpers.. not very nice because they related to search too. But maybe then into /src/bp/SearchBP (bp=business-process). And then in controllers/Search i use /bp/SearchBP that use some Model object with .save() DAO methods (SearchBP can use Domain methods and Search class can use Domain methods as well)
The question here: what class ant package would be nice for those methods? (i just did watch it in examples - there alway very simple usage of controllers that use domain object that why i ask)
yes, you can. Controllers are normal classes, you can add whatever you want. It may not be recommended to clutter them with helper methods, I personally would move them to another class, but you can do what you say.
ANSWER TO EDIT:
The name of the package is "irrelevant", won't change it too much :). You can put them under controllers.support.search which would mean controllers.support is a package with helper classes and the subpackage search contains helper classes and methods related to search.
One alternative (which I like more) is to create a Service layer for that, in a "services" package. You seem to come from a Spring background, so it should come naturally to you. These services are instantiated in the controller as required, or maybe just used via static methods, and do the main business logic. That way the controller only tackles the "higher level" logic.
Another alternative is to move as much of that logic as possible into the Model (avoidid the Anemic Domain Model), and using the Model classes from the controller.
As most decisions in development, which one is better depends on your experience, possible impact/limitations in the codebase, practices in your project... anyway, you can always refactor. Just choose the one that you are more used to (it seems to be Services approach) and code away :)
Any behaviour that's complicated enough to be described as "business logic" (rather than "presentation logic") belongs in the model, not the controller. If your model does nothing but map to/from a set of database tables, then it isn't doing its job properly. Things like permissions and access control, in particular, should be enforced by the model.

Castle.Windsor, ASP.NET MVC, Handling Null Resolution of Injection

Using Castle.Windsor in ASP.NET MVC (3.0) is there any way I can appropriately handle if one of my dependencies resolves null? For instance, say I have a IMembershipService.
class ServiceInstaller
{
// ...
void Install( // .. )
{
container.Register(
Component
.For<IMembershipService>()
.ImplementedBy<MembershipService>()
.LifeStyle.PerWebRequest
);
}
}
Okay, this works great. Now, perhaps not all of my site requires a user to be logged in. Let's assume that maybe my web host's database server crashes for a few hours. In that event, things that looked into the database, or tried to call on my ISession might return null.
What can I do in this case? I can write if(membershipService == null) a hundred times over, but that seems pretty dumb. Is there a built-in solution to say "Hey, if we have an error, do this..?"
I think that the service should never be null. If the database is down, the service should be returned nevertheless, but its methods should throw an exception, return null or some default value, depending on the semantic of the service.
Ciel, i had this problem just recently and found your question while looking for the answer.
Basically you should be using a typed factory to resolve your components at runtime in your wrapping component. The factory should return a default object if there is no match regarding the component you're looking for, default object that would implement whatever behavior is needed.
In the case of your IMembershipService, implement a NotCheckingMembershipService class inheriting the interface and doing nothing and make it the default for the components that won't need it. More specific membership services can be linked to specific controllers.
To do so you must create a generic "catch-all" implementation
public class NotCheckingMembershipService<T>: IMembershipService<T> where T: Controller
{
}
And register it as the default component for an open IMembershipService
_container.Register(
Component.For(typeof(IMembershipService<>))
.ImplementedBy(typeof(NotCheckingMembershipService<>))
.IsDefault());
Then simply register your custom membership services where needed. Resolution won't fail and you will always be able to call the interface.

Resources