Reputation: 21
Ok basically I am building a nuget package, and one of the things i would like the class to do is get the current applications controllers
So at the moment in the main project I do the following
using SolutionName.Website.MVC5.Controllers;
What I want to be able to do is something like
using this.Application.Controllers;
So it dynamicaly fills in the namespace for whatever solution the package is installed to.
I have sat here for an hour going through the possible permutations and have also googled a fair bit but not sure exactly what to google for
This is including API Controllers and I am Using MVC 5
Cheers
Martyn
Upvotes: 2
Views: 351
Reputation: 414
After using the information that @DavidL and @AndrewWhitaker gave me I thought I would post a little code snippet of how this can work in an MVC application as it maybe useful to go hand in hand with the question
I created the class below
public class GetControllerNameSpace
{
public static string NamespaceTag;
public void GetControllerNameSpaceMethod()
{
var NamespaceTagList = this.GetType().Assembly.GetTypes().Where(t => t.IsSubclassOf(typeof(Controller))).Select(x => x.Namespace).Distinct().ToList();
NamespaceTag = NamespaceTagList.FirstOrDefault();
}
}
and then in the RouteConfig.cs
using Controllers = GetControllerNameSpace;
This then lets me pass the information to my method here
private static IEnumerable<Type> GetTypesWithFixedControllerRouteAttribute(RouteCollection routes)
{
//This is where i am passing the variables
foreach (Type type in Assembly.GetAssembly(typeof(Controllers.HomeController)).GetTypes())
{
// Register any fixed actions
RegisterFixedActionRoutes(type, routes);
if (type.GetCustomAttributes(typeof(FixedControllerRouteAttribute), true).Any())
{
yield return type;
}
}
}
Please note that this works in my use case and may require more work when using multiple controller namespaces as mentioned in @DavidL's post
Upvotes: 1
Reputation: 33833
The following little piece of reflection will give you all the namespaces for files that end in "Controller".
var namespaces = this.GetType().Assembly.GetTypes()
.Where(t => t.Name.EndsWith("Controller"))
.Select(x => x.Namespace).Distinct().ToList();
You would need to call this from within your code, preferably in the Global.asax
.
Keep in mind that your controllers may be scattered across a number of namespaces, so additional logic will have to account for that. The number of namespaces is solely determined by how rigidly you structure your applications.
Alternatively, you can also pull types that inherit directly from 'System.Web.Mvc.Controller', as pointed out by Andrew Whitaker.
var namespaces = this.GetType().Assembly.GetTypes()
.Where(t => t => t.IsSubclassOf(typeof(Controller)))
.Select(x => x.Namespace).Distinct().ToList();
Upvotes: 2