Why do ASP.NET MVC Controller classes need to be public? - asp.net-mvc

When I make a change to the access modifier of a controller class it results in an error. If I make the accessibility of an action method non-public then it also results in an error (specifically a page not found error). Why is this the case?

By default if you not specify any access modifier for a class then it will default to internal in C#. Only code in the same assembly can access a class that is internal. So if your controller is internal, the code that creates a controller instance upon receiving a request would have to be in your assembly.
But controller creation code is present in the System.Web.Mvc assembly and by default DefaultControllerFactory is responsible for creating controllers. If your code is present in, for example, the MvcApplication1 assembly then DefaultControllerFActory can not find your controller classes without the public access modifier so it is not able to instantiate them.
If you want to build a tightly coupled ASP.NET MVC application (which it is not it designed for) then theoretically you could do it following way.
Get the MVC source code if available.
Then build your code in same assembly.

Related

Can you inject a controller into another controller in ASP.NET Core 6?

This is the situation, I'm using a Razor page to create an ASP.NET Core 6 MVC site for a friend, the thing is I'm trying to inject a controller into another controller and I'm getting an error while building the project.
Here is a screenshot showing the error:
I made sure to have the interface class added in Program.cs (I used AddTransient<,>() however it didn't worked with scoped or singleton either, I'm not sure of the difference between them).
So now I'm wondering if controllers are not supposed to be instantiated via DI.
If you guys need any extra information I'm more than pleased to share it!

How to move MVC 5 IdentityModels.cs into a separate assembly

I wonder if someone ran into the issue that I am having with trying to move ApplicationUser into Models project (where all other models reside including the ones related to Users table).
My test MVC 5 solution consists of a web project and two class libraries: one for data access layer (DAL) and the other for Models. I references AspNet.Identity.EntityFramework in all three projects.
In my DAL class I implement Repository pattern and a UnitOfWork. UnitOfWork extends IdentityDbContext<ApplicationUser>. ApplicationUser : IdentityUser is in Models class library.
In my web project UnitOfWork is instantiated using Autofac DI.
For regular controllers I defined a base class that inherits from Controller and takes IUnitOfWork as a parameter in the constructor. All controllers inherit from my custom base controller.
I ran into a problem with AccountController. It has two constructors: one with no parameters that seems to instantiate ApplicationDbContext, the other takes UserManager as a parameter.
The parameter-less constructor gives me most of the grief. I tried many things: make accountcontroller inherit from my custom base controller, then try to inherit it from the Controller class. At best I succeed in making my solution compile but when I test the app and fill out user Registration form I get 'Object is not instantiated' message. When I debug I see that the second constructor in AccountController gets called but UserManager is null there.
Any ideas? I would really appreciate somebody's brainy input into this.
Take a look at the SimpleSecurity Project. This project decouples ASP.NET Identity from the web application and puts ApplicationUser into an assembly separate from the web application. This project also has a version that uses SimpleMembership. For ASP.NET Identity look in the AspNetIdentity folder. The assembly for the security functions is in AspNetIdentity/SimpleSecurity.AspNetIdentity and the reference web application is in AspNetIdentity/SimpleSecurity.AspNetIdentity/RefApp.

How to register custom build Autofac.Module in Orchard?

I have a piece of code that encapsulates functionality that isn't specific to Orchard. However i need to make it available in Orchard via dependency injection. So, I built up an Autofac Module that registers all components (types), but I can't find a way to inform Orchard's Autofac Container about it.
From what i red, there are two ways to add a module to a container:
By supplying the module at to the ContainerBuilder (usually at start-up),
Or by updating the already built Container at runtime with a ContainerBuilder
I can approach the problem in the first way, but I rather do a variant of the second if there is such?
Just add a class deriving from Autofac.Module to your Orchard module and that's it. It will get automatically picked by Orchard during the container construction.
Piotr Szmyd's answer is fundamentally correct, but here's some more detail:
Your Orchard Module is the new .csproj that you've added to the Orchard.sln
Add Autofac as a reference to that csproj (make sure you use the version included with Orchard - not nuget. See here for more details about that problem)
Then add a class that derives from Autofac.Module and which implements Load(ContainerBuilder).
e.g.
using System;
using Autofac;
namespace MyCustom.Module.Namespace
{
public class LoaderModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<MyClass>().As<IMyInterface>();
}
}
}
As an additional note:
The Autofac registration code only gets invoked at application startup time.
If you are running with the site sitting locally in IIS and the code in VS, then the dynamic compilation nature of Orcahrd means that when you recompile the code, the application doesn't stop.
So in order for this Autofac registration code to be hit (and also for any channges to it to take effect) you have to iisreset to kill the application, so that it reloads the Autofac Registrations.

Get Assembly name from view

Currently I'm encountering the next problem: I have Locallization class which is static and specified in one of the assemblies in project(lets name it Proj.Common). And I have many plugins that are implementing some functionality. Each plugin is separate assembly that has it's own views. In order to localize message, I made function that gets plugin name via Assembly.GetCallingAssembly.GetName().Name. But view are compiled to separate assemblies and therefore when view is calling localization class i have no idea what plugin has that view. How may I obtain the name of Calling assembly, not assembly where views are compiled. Thank You. And Yes, My application is made as MVC 2 ASP.Net application.
Assuming you have access to the MVC objects in your function, you can call ViewContext.Controller.GetType().

How to properly decouple Structure Map dependency resolver from ASP.NET MVC web project?

While developing web project using ASP.NET MVC, I came up against a coupling problem.
When I build custom controller factory (or dependency resolver if using MVC 3), I need this factory to know somehow where to get dependencies from. Here's my code:
//from Global.asax.cs
DependencyResolver.SetResolver(new StructureMapControllerFactory());
class StructureMapControllerFactory: IDependencyResolver {
Container repositories;
public StructureMapControllerFactory()
{
repositories = new RepositoriesContainer();
}
//... rest of the implementation
}
class RepositoriesContainer: Container
{
public RepositoriesContainer()
{
For<IAccountRepository>().Use<SqlAccountRepository>();
//...
}
}
StructureMapControllerFactory class is responsible for injecting dependencies into a controller. As I said, it needs to know where to find these dependencies (I mean concrete classes, like services and repositories implementations).
I have a separate class library called MySite.Data, where all the implementation details live. Contracts, like IAccountRepository, live in library MySite.Contracts. Now, if I reference this MySite.Data library directly from MVC project, there will be a dependency between my site and implementation of its data retrieval. The question is how can I remove it? What are best practices in this situation?
I'm sure it does have a bunch of workarounds, just I haven't found any yet.
Well, as I see it, you can't do exactly that. Your MVC project really really needs to know about concrete classes it is going to use.
You will anyway have to provide those container registrations somewhere and you'll get the dependency on the project/assembly where that type is defined. Shortly, you have to reference MySite.Data from MVC project. Like that:
MySite.Data knows nothing about MVC project
MVC project knows the concrete repositories types to provide correct container registrations.
You can make life simpler with StructureMap Registry objects but you need to include those Registries somewhere as well. Typically those are in the main project or some "StructureMap-adapter" project but you'd need to make reference anyway.
I'd advise that you:
Use MVC3 and drop your custom IControllerFactory if you only use it for DI into your Controllers.
Use StructureMap Registry objects to provide each and every IoC registration ever needed.
Use StructureMap Assembly scanning capabilities to provide components discovery.
Use something much more common as a DependencyResolver, i.e. not a StructureMapControllerFactory but a CommonServiceLocator with StructureMap adapter instead.
Try to abstract from StructureMap itself inside your main app.
And, of course, don't be afraid of making references inside the main project - they have nothing about coupling. It doesn't decrease maintainability. But the wrong architecture does, so be worried about that, not simple reference.

Resources