I know the error "No parameterless constructor defined for this object" has been asked about a million times. My situation is different
I have a working app. Many many controllers and one area with lots of controllers. I just added a new area. I added a controller and then a link to that controller. NOW I get the
"No parameterless constructor defined for this object" error
I have seen and conquered this problem before but it really only happens like once every 5 months. And everytime I have totally forgotten ( repressed ) the answer.
Please help
Raif
Ok, so it seems that there are several reasons one might get this error. Not surprisingly none of them have ##$% all to do with not having a parameterless constructor. The two that I'm aware of are
1) if you are using an area and you, say, move a controller from one namespace to the new one and don't update the namespace to reflect the area you will get this error.
2) and this is my situation now, if you are injecting something into the constructor of the controller and the item you are injecting has a problem with it ( there are no instantiations, or it's not registered in your IOC registration or some other runtime error ) you will get this error.
If people can think of others they should list them here because I think there are several more causes for the error.
R
While I realize this doesn't truly answer your question, your answer helped me in my troubleshooting endeavors.
I just recently came across this same issue while using MVC Portable Areas from the MVC Contrib project. I found that any dll dependancies the portable areas had must also be included when scanning for assemblies during IOC registration, something along the lines of this:
ObjectFactory.Initialize(x => x.Scan(y =>
{
y.Assembly("PortableAreaAssemblyName");
}));
ObjectFactory.Configure(x =>
{
x.For<IClassInterfaceUsedByControllerConstructor>().Use<IntendedClassInstance>();
});
Related
I'm trying to dig into a memory leak in my MVC web app and one thing i noticed is that my DefaultRegistry for StructureMap had a duplicated a scan...scan.TheCallingAssembly():
public DefaultRegistry()
{
Scan(
scan =>
{
scan.TheCallingAssembly();
scan.WithDefaultConventions();
scan.TheCallingAssembly();
});
}
Would this cause a problem? Could it cause a memory leak? (Please be the problem). I'm publishing the correction tonight, so i'll find out eventually if that fixes the problem or not; but it would be nice to know for certain if duplicate scan methods have any side affects.
Also, is there any significance in the order in which the scan methods appear? Does scan.WithDefaultConventions() need to come last, or first, or does it matter?
Here's the relevant code in StructureMap: https://github.com/structuremap/structuremap/blob/master/src/StructureMap/Graph/AssemblyScanner.cs#L29-L30.
So no, StructureMap will not double scan the same assembly in any one call to Scan(). You could potentially create duplication if you do the same logical thing in multiple Scan() operations, but at least in the case up above those particular conventional registrations would not add the same type twice.
And no, it doesn't matter in what order you declare assemblies and registration conventions. The registration conventions would be executed in the order you define them, so you would see that reflected in dependency ordering in a few cases.
I've been working with MVC 3 for a little while at work and have been reviewing my code quite a bit. I'm using the session to store data I need across all actions/views.
I feel this is a bad idea, though I'm not entirely understanding of why. So I started reading around and found this post: Session variables in ASP.NET MVC
I'm currently accessing the session in my controller in this manner,
private SelectedReport Report
{
get
{
return Session["Report"] as SelectedReport;
}
set
{
Session["Report"] = value;
}
}
then Accessing it with this.Report
I've read that the way above is not optimal/good but I'm not certain why.
Why is my way not good/optimal? Why is the way in the link provided better?
(This might be better posed as a conceptual question but i'm not sure how to ask it that way, there are a few web/mvc concepts I think I'm missing. I was kind of just thrown into MVC/Web with no prior knowledge and was never sure where to start).
For error handling there are several libraries that can simplify things for you.
But beyond that, storing things on the session should only be done where you need the object In several places
Ideally if you need to expose one object from one view to the other, you could use a common base model that includes what the views need, or add stuff to the ViewData object instead of the session object.
And for error handling, fatal errors should be trapped in global.asax, and for warnings, I in particular use a base model class for all views that includes a warnings collection that is shown via master page.
I didn’t found short form for this question as subject…
Is it possible to inject already resolved instance’s property to dependency instance's constructor?
My question arises from MVC tutorial, created in 2009.
It seems like it’s a cyclic dependency to me.
Anyway, can I:
grab resolved ContactController (or its base Controller, Listing 3.) instance’s property ModelState
and inject it to its dependency ContactService (Listing 4.) instances dependency ModelStateWrapper (Listing 7.)
as constructor argument.
_service = new ContactManagerService(new ModelStateWrapper(this.ModelState)); (After Listing 8.)
How to accomplish above line with DI container?
I know that this validation that is happening in Service Layer can be done with data annotations or custom attributes, my question is not so much about design or architecture but possibility.
I have read Ninject wiki, some blog posts, answers, even found somewhat similar situations out there, but not exactly like this or was not able to figure out how to accomplish this or is it possible at all with Ninject.
BR,
No you can't
To see the problem you must think about the order in which the objects are created
var modelStateWrapper = new ModelStateWrapper();
var service = new ContactService(modelStateWrapper);
var controller = new ContactController(service);
This means the modelstate wrapper is created longtime before the controller and therefore it is impossible to pass the model state to the ModelStateWrapper's constructor. The only thing that is doable is to use Property Injection somewhere but this is only a workaround for the actual problem which is that you have a cyclic dependency.
The implementation also ties the service tightly to the controller. Consider using ModelValidators instead.
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.
We are developing what is becoming a sizable ASP.NET MVC project and a code smell is starting to raise its head.
Every controller has 5 or more dependencies, some of these dependencies are only used for 1 of the action methods on the controller but obviously are created for every instance of the controller.
I'm struggling to think of a good way to reduce the number of objects that are created needlessly for 90% of calls.
Here are a few ideas I'm toying around with:
Splitting the controllers down into smaller, more targeted ones.
Currently we have roughly a controller per domain entity, this has led to nice looking URLs which we would like to emulate, meaning we would end up with a much more complicated routing scheme.
Passing in an interface wrapping the IoC container.
This would mean the objects would only be created when they were explicitly required. However, this just seems like putting lipstick on a pig.
Extending the framework in some way to achieve some crazy combination of the two.
I feel that others must have come across this same problem; so how did you solve this or did you just live with it because it isn't really that big a problem in your eyes?
I've been pondering solutions to this very problem, and this is what I've come up with:
Inject your dependencies into your controller actions directly, instead of into the controller constructor. This way you are only injecting what you need to.
I've literally just whipped this up, so its slightly naive and not tested in anger, but I intend to implement this asap to try it out. Suggestions welcome!
Its of course StructureMap specific, but you could easily use a different container.
in global.asax:
protected void Application_Start()
{
ControllerBuilder.Current.SetControllerFactory(
new StructureMapControllerFactory());
}
here is structuremapcontrollerfactory:
public class StructureMapControllerFactory : DefaultControllerFactory
{
protected override IController GetControllerInstance(Type controllerType)
{
try
{
var controller =
ObjectFactory.GetInstance(controllerType) as Controller;
controller.ActionInvoker =
new StructureMapControllerActionInvoker();
return controller;
}
catch (StructureMapException)
{
System.Diagnostics.Debug.WriteLine(ObjectFactory.WhatDoIHave());
throw;
}
}
}
and structuremapcontrolleractioninvoker (could do with being a bit more intelligent)
public class StructureMapControllerActionInvoker : ControllerActionInvoker
{
protected override object GetParameterValue(
ControllerContext controllerContext,
ParameterDescriptor parameterDescriptor)
{
object parameterValue;
try
{
parameterValue = base.GetParameterValue(
controllerContext, parameterDescriptor);
}
catch (Exception e)
{
parameterValue =
ObjectFactory.TryGetInstance(
parameterDescriptor.ParameterType);
if (parameterValue == null)
throw e;
}
return parameterValue;
}
}
There is the concept of "service locator" that has been added to works like Prism. It has the advantage of reducing that overhead.
But, as you say, it's just hiding things under the carpet. The dependencies do not go away, and you just made them less visible, which goes against one of the goals of using DI (clearly stating what you depend on), so I'd be careful not to overuse it.
Maybe you'd be better served by delegating some of the work. If there is some way you were intending to re-partition your controller, you might just want to create that class and make your controller obtain an instance of it through DI.
It will not reduce the creation cost, since the dependencies would still be resolved at creation time, but at least you'd isolate those dependencies by functionality and keep your routing scheme simple.
I would consider separately the problem of dependencies and creation of dependent objects. The dependency is simply the fact that the controller source code references a certain type. This has a cost in code complexity, but no runtime cost to speak of. The instantiation of the object, on the other hand, has a runtime cost.
The only way to reduce the number of code dependencies is to break up the controllers. Anything else is just making the dependencies a bit prettier, as you say. But making the dependencies (as opposed to instantiation of the dependent objects, which I'll cover in a second) prettier may well be enough of a solution that you don't need to break up the controllers. So IoC is a decent solution for this, I think.
Re: creating the objects, you write, "...some of these dependencies are only used for 1 of the action methods on the controller but obviously are created for every instance of the controller." This strikes me as the real problem, rather than the dependency, per se. Because it's only going to get worse as your project expands. You can fix this problem by changing the instantiation of the objects so that it does not happen until they are needed. One way would be to use properties with lazy instantiation. Another way would be to use arguments to your action methods with model binders which instantiate the objects you need. Yet another way would be to write functions which return the instances you need. It's hard to say which way is best without knowing the purpose of the objects you're using.
Your controllers may be becoming too "Fat". I suggest creating an application tier which sit beneath your controllers. The application tier can encapsulate a lot of the orchestration going on inside your controller actions and is much more testable. It will also help you organize your code without the constraints of designated action methods.
Using ServiceLocation will also help (and yes, I'm essentially reiterating Denis Troller's answer- which probably isn't good but I did vote his answer up).