I know that this is a duplicate question but i can't find answer to my error.
I'm trying to show a list of my rooms saved in database but i get next error:
Server Error in '/' Application.
No parameterless constructor defined for this object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.MissingMethodException: No parameterless constructor defined for this object.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[MissingMethodException: No parameterless constructor defined for this object.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache) +98
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) +241
System.Activator.CreateInstance(Type type, Boolean nonPublic) +69
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +67
[InvalidOperationException: An error occurred when trying to create a controller of type 'HotelProjectFinal.Controllers.RoomController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +182
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +80
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +74
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +232
System.Web.Mvc.<>c__DisplayClass6.<BeginProcessRequest>b__2() +49
System.Web.Mvc.<>c__DisplayClassb`1.<ProcessInApplicationTrust>b__a() +13
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Func`1 func) +124
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +98
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8969412
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
But i have a constructor withou a parameter:
namespace HotelProjectFinal.Controllers
{
public class RoomController : Controller
{
private IRoomRepository repository;
public RoomController(IRoomRepository roomRepository)
{
repository = roomRepository;
}
public ViewResult List()
{
return View(repository.Rooms);
}
}
}
My view is :
#model IEnumerable<HotelProjectFinal.Models.Room>
#{
ViewBag.Title = "List";
}
#foreach (var p in Model)
{
<div class="item">
<h3>#p.Room_number</h3>
#p.Room_Type
<h4>#p.Room_Type.Price.ToString("c")</h4>
</div>
}
I am using ninject:
public class NinjectControllerFactory : DefaultControllerFactory
{
private IKernel ninjectKernel;
public NinjectControllerFactory()
{
ninjectKernel = new StandardKernel();
AddBindings();
}
protected override IController GetControllerInstance(RequestContext requestContext,
Type controllerType)
{
return controllerType == null
? null
: (IController)ninjectKernel.Get(controllerType);
}
private void AddBindings()
{
ninjectKernel.Bind<IRoomRepository>().To<EFRoomRepository>();
}
}
}
You've got a controller factory, but the fact that the stacktrace says nothing about Ninject suggests you have forgotten to tell MVC about it.
You could fix that by adding a line to tell it that.
However the recommended practice is to hook Ninject in by adding a NuGet reference to Ninject.MVC3. There are docs about it on the associated Ninject MVC3 wiki.
Please try changing your constructors to the following:
public RoomController() { } // You were missing this parameterless constructor
[Inject]
public RoomController(IRoomRepository roomRepository)
{
repository = roomRepository;
}
Ninject is looking for a parameterless constructor because you haven't specified [Inject] above constructor that you wish to use for dependency injection. This has confused "Ninject" and caused an exception to be thrown.
The primary DI pattern is Constructor Injection. When activating an instance of a type Ninject will choose one of the type’s constructors to use by applying the following rules in order:-
If a constructor has an [Inject] attribute, it is used (but if you apply the attribute to more than one, Ninject will throw a NotSupportedException at runtime upon detection).
If no constructors have an [Inject] attribute, Ninject will select the one with the most parameters that Ninject understands how to resolve.
If no constructors are defined, Ninject will select the default parameterless constructor (assuming there is one).
More information can be found here:
https://github.com/ninject/ninject/wiki/Injection-Patterns
As pointed out by Ruben, [Inject] attribute pollutes the controller with external concerns.
This ties your code to a specific container. (Although Ninject does permits the customization of the specific attribute to look for, the point remains – you’re polluting an interface with external concerns.)
Your actual problem probably relies in a missing reference to Ninject.MVC3
Even though IRoomRepository could be null, that doesn't make it a parameterless constructor. At first glace, it looks like your IoC isn't wired up correctly for IRoomRepository. With no IoC, or misconfigured IoC, the controller activator looks for a parameterless constructor for your controllers.
// This is a parameterless constructor.
public RoomController()
{ }
// This is not a parameterless constructor.
public RoomController(IRoomRepository roomRepository)
{
repository = roomRepository;
}
Edit, Are you using Ninject.Mvc and your base MvcHttpApplication is implementing NinjectHttpApplication?
Related
I am trying to create a project. That's why I downloaded a startup template from this link. Then I tried to configure with asp.net core. I set the connection string as "Default": "User ID=postgres;Password=**********;Host=localhost;Port=5432;Database=LibraryManagementDb;Pooling=true;". and then changed UseSqlServer to UseNpgsql in LibraryManagementDbContextConfigurer class.
`
public static void
Configure(DbContextOptionsBuilder<LibraryManagementDbContext>
builder, string connectionString)
{
builder.UseNpgsql(connectionString);
}
public static void
Configure(DbContextOptionsBuilder<LibraryManagementDbContext>
builder, DbConnection connection)
{
builder.UseNpgsql(connection);
}
`
and add the below code to DbContext class
`
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ApplicationLanguageText>()
.Property(p => p.Value)
.HasMaxLength(100); // any integer that is smaller than 10485760
}
`
and removed all migration classes from the Migration folder and run add-migration Initial_Migration command in the package manager console
but I got the Exception has been thrown by the target of an invocation. error
this is the whole exception
`
PM> add-migration Initial_Migration
Build started...
Build succeeded.
System.Reflection.TargetInvocationException: Exception has been
thrown by the target of an invocation.
---> System.TypeLoadException: Method 'get_Info' in type
'Microsoft.EntityFrameworkCore.Infrastructure.
Internal.NpgsqlOptionsExt
ension' from assembly 'Npgsql.EntityFrameworkCore.PostgreSQL,
Version=2.1.0.0, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7'
does not have an implementation.
at Microsoft.EntityFrameworkCore
.NpgsqlDbContextOptionsExtensions.UseNpgsql[TContext]
at LibraryManagement.EntityFrameworkCore
.LibraryManagementDbContextConfigurer
.Configure(DbContextOptionsBuilder`1 builder, String
connectionString) in D:\6.0.0\aspnet-
core\src\LibraryManagement.EntityFrameworkCore
\EntityFrameworkCore\LibraryManagementDbContextConfigurer.cs:line
10
at LibraryManagement.EntityFrameworkCore
.LibraryManagementDbContextFactory.CreateDbContext(String[] args)
in D:\6.0.0\aspnet-core\src\LibraryManagement.EntityFrameworkCore
\EntityFrameworkCore\LibraryManagementDbContextFactory.cs:line 17
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[]
arguments, Signature sig, Boolean constructor, Boolean
wrapExceptions)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj,
BindingFlags invokeAttr, Binder binder, Object[] parameters,
CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[]
parameters)
at Microsoft.EntityFrameworkCore.Design
.Internal.DbContextOperations.CreateContextFromFactory(Type
factory,
Type contextType)
at
Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.
<>c__DisplayClass16_0.<FindContextFactory>b__1()
at Microsoft.EntityFrameworkCore.Design.Internal
.DbContextOperations.CreateContext(Func`1 factory)
at Microsoft.EntityFrameworkCore.Design.Internal
.DbContextOperations.CreateContext(String contextType)
at Microsoft.EntityFrameworkCore.Design.Internal
.MigrationsOperations.AddMigration(String name, String outputDir,
String contextType, String namespace)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor
.AddMigrationImpl(String name, String outputDir, String
contextType,
String namespace)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor
.AddMigration.<>c__DisplayClass0_0.<.ctor>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor
.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor
.OperationBase.Execute(Action action)
Exception has been thrown by the target of an invocation.
`
How can I resolve this??? Please help...
By updating 'Npgsql.EntityFrameworkCore.PostgreSQL' solved this problem
If you define the following two properties on your model class this will crash with a NullReferenceException during model binding:
public Customer Customer { get; private set; } //set in the action method
public bool Name => Customer.Name;
This is because Customer is still null during model binding and ASP.NET MVC calls the getter for Name.
The stack is:
System.ComponentModel.ReflectPropertyDescriptor.GetValue(Object component) +525
System.Web.Mvc.ModelMetadata.get_Model() +34
System.Web.Mvc.DataAnnotationsModelValidator.Validate(Object container) +151
System.Web.Mvc.<Validate>d__1.MoveNext() +387
System.Web.Mvc.DefaultModelBinder.OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext) +163
System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +83
System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +1754
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +460
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +137
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +982
System.Web.Mvc.<>c__DisplayClass22.<BeginExecuteCore>b__1e() +39
System.Web.Mvc.Async.AsyncResultWrapper.<.cctor>b__0(IAsyncResult asyncResult, Action action) +21
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +53
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +36
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +38
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +44
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +65
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +399
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +137
From the stack it looks like model validation is querying all getters. I'm not using model validation.
How can I deal with this situation? Can I make ASP.NET MVC not call all getters without any (apparent) reason?
So the Model Binder new's up an instance of your Model, then is probably doing reflection over the model's properties to look for named matches with the values in the FormCollection. What's happening is that the Customer prop is null when that dangerous Name prop is called, thus the NullRef.
The order by which .NET is checking those properties might not be actually random, but your code will be much improved by just treating it as such. Calling a method/prop directly on a Class that's nullable by default is a terrible idea, unless you check it for null. You have two options here, either (1) redesign your Model class so that the Constructor initializes the "Customer" property, or (b) add a null-check in that "Name" method.
Here's the easiest approach to just null-checking it when you grab it:
public bool Name => Customer?.Name ?? false;
This does not solve the underlying issue, which is that you have a Model that has nullable props chained together. Don't worry about your Model's constructor messing up your model binding. The Model Binder will (1) initialize your model class, then (2) try to hydrate it. So initializing the Customer class/prop in your Model's constructor won't impact any mapping of UI fields to say that Customer's fields.
The DefaultModelBinder in MVC version 5.2.3 does validation in addition to binding, and there is no way to shut it off completely. Other SO posts mention turning off the implicit required attribute for value types with the following line of code in your Global.asax.cs, Application_Start() method...
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
See: https://stackoverflow.com/a/2224651 (which references a forum with an answer directly from the asp.net team).
Given your stack trace, that might fix your immediate problem. However, that probably won't be enough due to the DefaultModelBinder calling the getters even outside of its validation code for no stated reason (the source code makes no comment as to why it does that).
To solve the problem on my projects, where I use calculated properties all the time similar to your example, I implemented a custom model binder based on the original DefaultModelBinder source code that does not call any getters.
See a more detailed explanation and my full solution here: https://stackoverflow.com/a/54431404/10987278.
I'm trying to get Mvc4 routing set up in an existing sitecore WebForms application.
I've added the following:
routes.MapPageRoute("WebForm", "WebForm", "~/WebForm1.aspx");
Navigating to /WebForm gives the following exception:
[NullReferenceException: Object reference not set to an instance of an object.]
System.Web.AsyncStepCompletionInfo.RegisterBeginUnwound(IAsyncResult asyncResult, Boolean& operationCompleted, Boolean& mustCallEndHandler) +32
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +516
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +287
I faced with the same exception when enabled MVC on Sitecore CMS. I found that the reason is that Sitecore accepts only IAsyncHttpHandler routes.
Technically Sitecore.Mvc.Pipelines.Loader.InitializeRoutes pipeline wraps your handler with RouteHandlerWrapper and invokes it through async RouteHttpHandler that throws the exception in case your handler is not inherited from IHttpAsyncHandler.
To avoid it you should register your routes after Sitecore.Mvc.Pipelines.Loader.InitializeRoutes pipeline in Sitecore.Mvc.config:
<initialize>
<processor type="Sitecore.Mvc.Pipelines.Loader.InitializeGlobalFilters, Sitecore.Mvc"/>
<processor type="Sitecore.Mvc.Pipelines.Loader.InitializeControllerFactory, Sitecore.Mvc"/>
<processor type="Sitecore.Mvc.Pipelines.Loader.InitializeRoutes, Sitecore.Mvc"/>
<!-- Register your routes here -->
</initialize>
Alternatively you can make you handler to work asynchronous:
public class MyHandler : IHttpAsyncHandler
{
public void ProcessRequest(HttpContext context)
{
// do your work here
}
public bool IsReusable { get { return false; } }
protected delegate void AsyncProcessorDelegate(HttpContext context);
private AsyncProcessorDelegate _processorDelegate;
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
{
_processorDelegate = new AsyncProcessorDelegate(ProcessRequest);
return _processorDelegate.BeginInvoke(context, cb, extraData);
}
public void EndProcessRequest(IAsyncResult result)
{
_processorDelegate.EndInvoke(result);
}
}
Background is ASP.NET WebForms application using Entity Framework with Repository and UnitOfWork pattern. Note that the application is also configured to use the out-of-proc StateServer for Session mgt which I understand means that anything I store in session must be serializable.
I also have an HttpModule configured to create a UnitOfWork object (which contains my entity context object) upon each HttpRequest, store it in HttpContext.Current.Items, and of course dispose it at the end of each request.
My UnitOfWork class itself contains properties for each of my repositories as well as the entity context itself.
In an effort to allow more flexible testing in the future, I created an IObjectContext interface with signatures for the methods and properties on my entity context, and I created a partial class for my entity context and inherited from it.
public class UnitOfWork : IUnitOfWork
{
private IObjectContext context;
}
public UnitOfWork(IObjectContext context)
{
this.context = context;
}
public partial class MyEntities : IObjectContext
{
}
private static void ApplicationBeginRequest(Object source, EventArgs e)
{
if (!HttpContext.Current.Items.Contains("UnitOfWork"))
{
IUnitOfWork unitOfWork = new UnitOfWork();
HttpContext.Current.Items.Add("UnitOfWork", unitOfWork);
}
}
private void ApplicationEndRequest(object sender, EventArgs e)
{
if (HttpContext.Current.Items["UnitOfWork"] != null)
((IUnitOfWork)HttpContext.Current.Items["UnitOfWork"]).Dispose();
}
The goal here is ultimately to allow me to fake my entity context object to create for example, an in-memory context for testing purposes.
Everything was going fine until I started getting "not marked as serializable" exceptions on my entity context object. Obviously my first thought was to just add [Serializable] to my partial entity context class, but then it started complaining that System.Data.Objects.ObjectContext in Assembly System.Data.Entity was not marked as serializable (which I obviously don't have any control over).
What am I missing here? It seems like I can't store my entity context object in HttpContext.Current.Items, which I must do for my unit of work pattern implementation.
Is this because I'm using the ASP.NET State Server instead of in-proc session mgt? Surely there's a way to store the context for the life of the HTTP request if you're using the State Server?
Just feel like I'm missing something obvious here. I've added [Serializable] to everything from the UnitOfWork to the MyEntities context to each repository class. Still can't get past the entity context itself.
Any ideas?
UPDATE (Adding Stack Trace):
[SerializationException: Type 'myDAL.Model.myEntities' in Assembly 'myDAL, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.]
System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(RuntimeType type) +14324629
System.Runtime.Serialization.FormatterServices.GetSerializableMembers(Type type, StreamingContext context) +408
System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo() +420
System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder) +532
System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Write(WriteObjectInfo objectInfo, NameInfo memberNameInfo, NameInfo typeNameInfo) +969
System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck) +633
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header[] headers, Boolean fCheck) +322
System.Web.Util.AltSerialization.WriteValueToStream(Object value, BinaryWriter writer) +1487
[HttpException (0x80004005): Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode.]
System.Web.Util.AltSerialization.WriteValueToStream(Object value, BinaryWriter writer) +2485899
System.Web.SessionState.SessionStateItemCollection.WriteValueToStreamWithAssert(Object value, BinaryWriter writer) +49
System.Web.SessionState.SessionStateItemCollection.Serialize(BinaryWriter writer) +746
System.Web.SessionState.SessionStateUtility.Serialize(SessionStateStoreData item, Stream stream) +336
System.Web.SessionState.SessionStateUtility.SerializeStoreData(SessionStateStoreData item, Int32 initialStreamSize, Byte[]& buf, Int32& length, Boolean compressionEnabled) +99
System.Web.SessionState.OutOfProcSessionStateStore.SetAndReleaseItemExclusive(HttpContext context, String id, SessionStateStoreData item, Object lockId, Boolean newItem) +3828904
System.Web.SessionState.SessionStateModule.OnReleaseState(Object source, EventArgs eventArgs) +1021
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +165
The stack trace indicates that there is a non-serializable object in the session, not in the context. Double check that you did not put your data object in session by mistake.
Putting it into the context request should not be giving this error.
Edit: This is fixed -- See Solution below
Solution: First I incorrectly had my node defined in /shared/web.config instead of the web.config in the root of the WebUI project. I also had not correctly defined my connection string within web.config. I have pasted the proper web.config sections below:
<configuration>
<configSections>
<section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor"/>
<!--more sectiongroup and sections redacted for brevity -->
</configSections>
<castle>
<components>
<component id="ProdsRepository" service="DomainModel.Abstract.IProductsRepository, DomainModel" type="DomainModel.Concrete.SqlProductsRepository, DomainModel">
<parameters>
<connectionString>Data Source=.\SQLExpress;Initial Catalog=SportsStore; Integrated Security=SSPI</connectionString>
</parameters>
</component>
</components>
</castle>
I also had to adjust the method body of WindsorControllerFactory.cs (IoC Container) to return null for invalid requests like so:
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
if (controllerType == null)
return null;
else
return (IController)container.Resolve(controllerType);
}
End of Solution
I'm following the book Pro ASP.NET MVC2 by Sanderson. I've implemented the IoC container and gotten the web.config straightened out. When I attempt to run my application I get the error "No parameterless constructor defined for this object"
After some searching I found this exact issue on SO here. The solution is to create the constructor with no parameters but I'm having an issue doing this. I've pasted the code from ProductsController.cs below
namespace WebUI.Controllers
{
public class ProductsController : Controller
{
private IProductsRepository productsRepository;
public ProductsController(IProductsRepository productsRepository)
{
this.productsRepository = productsRepository;
}
public ViewResult List()
{
return View(productsRepository.Products.ToList());
}
}
}
Above the public ProductsController that has parameters I tried doing:
public ProductsRepository() : this(new productsRepository())
{
}
I'm unclear about exactly what needs to go after the "new". IProductsRepository doesn't seem to work and neither does what I have written. I have pasted the stack trace below:
Stack Trace:
[MissingMethodException: No parameterless constructor defined for this object.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache) +86
System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache) +230
System.Activator.CreateInstance(Type type, Boolean nonPublic) +67
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +80
[InvalidOperationException: An error occurred when trying to create a controller of type 'WebUI.Controllers.ProductsController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +190
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +68
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +118
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +46
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +63
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +13
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8682818
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Any help would be greatly appreciated.
Edit: Posting WindsorControllerFactory.cs code:
namespace WebUI
{
public class WindsorControllerFactory : DefaultControllerFactory
{
WindsorContainer container;
// The contructor:
// 1. Sets up a new IoC container
// 2. Registers all components specified in web.config
// 3. Registers all controller types as components
public WindsorControllerFactory()
{
// Instantiate a container, taking config from web.config
container = new WindsorContainer(new XmlInterpreter(new ConfigResource("castle")));
// Also register all the controller types as transient
var controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
where typeof(IController).IsAssignableFrom(t)
select t;
foreach (Type t in controllerTypes)
container.AddComponentLifeStyle(t.FullName, t, Castle.Core.LifestyleType.Transient);
}
// Constructs the controller instance needed to service each request
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
return (IController)container.Resolve(controllerType);
}
}
}
Edit2: Pertinent Web.config nodes:
<configSections>
<section name="castle"
type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler,
Castle.Windsor" />
</configSections>
<castle>
<components>
<component id="ProdsRepository"
service="DomainModel.Abstract.IproductsRepository, DomainModel"
type="DomainModel.Concrete.SqlProductsRepository, DomainModel"></component>
<parameters>
</parameters>
</components>
</castle>
You need to configure a custom controller factory in order to wire up your DI framework inside Application_Start method in global.asax. So for example if you are using Unity as DI framework you could:
ControllerBuilder.Current.SetControllerFactory(
typeof(UnityControllerFactory)
);
Check out this blog post for more information.
you can make use of setter based injection
public class ProductsController : Controller
{
private IProductsRepository productsRepository;
public ProductsController()
{
}
public ViewResult List()
{
return View(productsRepository.Products.ToList());
}
public IProductsRepository MyRepository
{
get
{
return productsRepository;
}
set
{
productsRepository = value;
}
}
}
here , you need to manually set the MyRepository.
but best would be , if you register your repository to a container and beliving that you are using Unity framework , so you can do it by IUnityContainer.RegisterType() method