Best Practice - Share UnityContainer across Tiers in Asp.net MVC? - asp.net-mvc

I have a UnityContainer that gets it's configuration information at runtime in the global.asax file of an MVC web app.
I also have services in another assembly that need access to this container so that they can perform resolutions manually.
How can I best share the two? I don't want to have a reference between my Data assembly and MVC, but I want the data assembly to have access to the UnityContainer that was configured by the web app.
I'm wondering what others are doing in this situation.

I just registered the container into itself, and then let the dependencies cascade throughout the referenced tiers.
ie
// configure container
blah
blah
blah
// register itself
Container.RegisterInstance(Container);
Then anyone that needs it just has it as a dependent property or constructor param.

I am using StructureMap (similar tool) and generally share my configuration across projects in a solution. This means that they are not directly sharing the same object per-se unless they are working in the same context. In a simple application where the website is loading the assembly to perform work from the controller to the business layer and then into the dal...they are indeed using the same object. But as soon as you need to put your tier's into physically separate layers (hardware) then the config can go with it. This becomes a deployment issue at that time.

Related

Configuring MassTransit in Onion Architecture with ASP.NET MVC and Ninject

I am currently setting up a simple MVC application that is structured as an Onion Architecture. For simplicity's sake, assume that I have the following projects (disregarding the business and database layers, at the moment):
Sample.Web - This is the ASP.NET MVC Application
Sample.Application - This contains the application services.
Sample.Infrastructure - This contains the infrastructure services.
For now, I am using Ninject (although that will likely change). So, with Ninject MVC, I am registering the Application and Infrastructure services at startup, using the Sample.Web to act as the composition root. Application services from Sample.Application are injected into the controllers, and that is straightforward enough and working well.
Where I am having issues, though, is determining how to properly initialize MassTransit, in the equation. Ideally, I want to have a generic interface to wrap the ConsumeContext instance and allow for me to set up the events. I do not seem to be able to fully set up the instance from within Sample.Infrastructure, as the infrastructure does not/should not know what the events are. I would assume that the consumer classes should exist in Sample.Application, and I do not think that the infrastructure should have a dependency on knowing the consumers.
On startup, System.Web will load the NinjectModule from each System.Application and System.Infrastructure. Does that mean that System.Web should have explicit knowledge of the consumer classes, so that it can configure the IBusControl instance, or is there a more elegant solution?
Right now, the path that I think I am going down is that Sample.Web will load the NinjectModule instances, as it does, and then I will configure the ConsumeContext from Application_Start, after I have explicitly loaded the consumers. However, that would mean that I would have to rebuild/redeploy Sample.Web if I ever add consumers, which is less than ideal and is the root of my concerns. Assuming that consumers are defined within Sample.Application, and all event publications and subscriptions exist within Sample.Application, having to touch either Sample.Web or Sample.Infrastructure to add a consumer is code smell.
Many thanks, in advance.
Edit
As always, after hitting submit, something else comes to mind. I think that one possible solution may be to have Sample.Web as Sample.Application for the known endpoints. Since all events will be published and subscribed from Sample.Application, it would make some sense to have Sample.Web create the actual instance in Sample.Infrastructure and compose the endpoints from what it learns from Sample.Application.
Am definitely open to other solutions, though.

ASP.NET MVC - Where does the Authentication Layer go?

I have an MVC solution setup like this, with three 'projects'.
Web (MVC Project, Views, Controllers, ViewModels)
Models (Domain Objects)
Persistence (nHibernate Mapping, SessionFactory)
I need to begin building the repositories, and was going to start with the Authentication Model. Basically following the default MVC template, have an IMembershipService and an IFormsAuthenticationService and related classes (using custom code, not built in authentication providers).
My question is ...where should this go? My Repositories will need access to both my Domain objects and my Persistence Layer. However I keep reading that any kind of 'coupling' means it is a bad design. So I am hesitant to create a fourth project for the Repositories/Services that references the Models/Persistence ...but I can't really find any other way to do it logically.
This is very subjective.
Do what makes sense to you and your team.
I throw them in with the rest of my Repositories. I mean a User is pretty central to any application right? Does a User own anything? If so then isn't he an root?
Repositories are part of the domain.
Tension will always exist between reducing assembly references and minimizing number of projects. That is, you can make each assembly reference fewer dependencies by breaking up functionality into more fine-grained assemblies; however, excessive division of a project into many assemblies requires more effort to manage.
Another point worth mentioning is that authentication has a couple sides to it. One is managing the model around Users, Roles, Permissions, etc. - this is a domain concern. The other is interfacing with the context of execution (whether this is an ASP.Net app, WinForms, etc.) - this is an infrastructure concern. Consequently, I end up with a small service in my MVC project or WinForms project that performs functions like setting Forms Authentication cookies, or setting the current thread principal, etc.
The Separated interface pattern says that your models and repository interfaces should be in a seperate assembly, apart from the GUI and the actual repository implementation. This is to be able to switch implementations later on and to be able to simplify testing.
I would have no problem with putting the interfaces along with the repository interfaces and the actual implementation in the mvc project or the repository project. It's quite easy to move stuff later on if you use a IoC container.

Castle Windsor with ASP.NET MVC 2 Areas

Been lurking for a few months and decided to jump in with a question. I am very new to Windsor and IoC in general. I can get Windsor to work with my MVC2 project with no problem. The project I am working on is a "portal" of multiple applications under one MVC2 project using the new Areas concept. In this scenario, each Area will actually be a separate application inside the "portal". We are doing this to effectively share a LOT of common code, views, authentication, and cross-application functionality. Many of our apps link to one another, so it made sense after discussing it to combine them into one project.
What I am wondering how to do is actually allow different Areas to inject different concrete classes? In my limited understanding, the Application_Start is governing building the container and assigning it as the controller factory. I don't necessarily want to do all the injection at the application level. We have a config system where we have a config.xml at the root of every Area and those settings override any root settings. I would like to continue that trend by having the injections for each Area be read by the Area's config.xml (an inheritance similar to Webforms web.config where the config in a lower folder overrides settings in a parent folder).
Example: I would have an ILogHandler which would need a different concrete implementation depending on which Area of the application I am in. So I would need to inject something different depending on where I am at in the application.
I can easily do this using factories since each area could have it's own set of factories, but I am attempting to take this opportunity to learn about IoC and what the benefits/drawbacks are. Any help would be appreciated.
Just FYI - you absolutely must not have area-specific security code. For example, a factory or invoker which injects [Authorize] attributes depending on the current area could open your application to attack.
Contrast this with a MyAreaBaseController, which all controllers in your area must subclass. [Authorize] attributes (and other security-related code) here are OK since they're applied to the type and are independent of any concept of "area".

What is the correct layer to configure your IoC container when using a service layer?

I have a medium sized asp.net MVC app. It consumes a service layer that handles all the repository use, calling domain services, etc. My controller actions are very slim -- they basically call a service class, get a response and show that respose. Most components are interface based with some poor man's DI. The app is growing, needs better testing support, and starting to call out for an IoC container.
Everything I read (such as this SO question) states that I should configure the IoC at the application root. This makes sense to me if I were using repositories right from my controller actions and needed DI at the controller level, but I'm not. It seems like I'd want my composition root in my service layer. I keep thinking that I don't want my web.config (or another config) at the UI layer even mentioning/seeing/hearing about a repository, credit card processor, etc.
Am I thinking about this the right way or do I just need to get over it?
I have the same situation as you and I tackle it as follows.
The general rule I use is what ever has a global.asax or something similar, it needs to execute the code that registers the IoC components. Another way of putting it is that you need to run it one for each different process that is running (i.e. the website is in one process and the service is in another).
In my case I do this once for the mvc website global.asax and again for the server. In this case the registrations that get made would be different between the service and the website.
In addition I do one more thing. Due to the fact that I reuse components between the mvc app and the service (i.e. logging) I have a third core component that registers the core IoC components for the system and this component is called by the both the website and services registrations. Hence I anything that is common between the service and the website go into the core registration and then anything that is different goes into the 'interface' specific registration.
Hope that helps.
You just need to get over it :)
Having your Composition Root in the application root doesn't require you to have a lot of DI Container stuff in web.config. You can if you will, but it's optional. What is not optional when putting the Composition Root in the application root is that you need to have some DI code in Global.asax.
You may find it irrelevant because your Controllers are so thin, but that's not the real point. The actual point is that you (the abstract 'you') want to postpone coupling classes until the last responsible moment. The earlier you couple types, the less flexibility you have.
If you couple classes in the service layer, you make an irreversible decision at that point. If it later turns out that you need to compose those services differently, you can't - not without recompiling, that is.
If there was a major benefit of doing it, I can understand why you would want to, but there isn't. You may as well wait composing all components untill you absolutely must do so - and that's in the application's entry point.
Coming from a Java perspective, I use the Spring framework for my IoC container. With it, the container really is application-wide. Although you can have different configuration files for different layers (a persistence config file, a services config file, a controller config file, etc), all of objects (beans in Java lingo) go into the container.
I think this still ok though because there is no coupling between classes as you mentioned. A view does not need to know about a credit card processor, just because they are in the same IoC container. These classes will receive (by injection) only the dependencies they need, and are not concerned with other objects in the container.

How to structure, partition, and build large MVC application for deployment in small incremental pieces?

We will be developing a very large vertical market web application, and are leaning toward the MVC approach.
It will have 1 Master Page common to all views in the application.
The master will provide a navigation/search framework for the entire application
that will allow users to search and select entities and then navigate to a function to perform.
The database model will have 700 to 1000 tables.
The application will have hundreds of controllers.
Controllers and their views could be grouped together into one of the many (20-50) subsystems in the application.
(We are looking at an areas approach to aide in organization).
We want to be able to deliver enhancements/updates in small functional pieces.
These might me a new function, a bug fix, customer dependent functionality, or optional modules separately purchased by the enduser.
We spent too many years developing/supporting and delivering one large windows vb app exe.
We would like to take another approach.
Management does not want to deliver one large application. They want to be able to deliver
small incremental pieces when necessary.
We may want to create a deliverable that contains one controller, and only a couple views, and a portion of the model.
To deliver it, we want to copy a dll to a bin folder, and create a View folder and copy in the new view(s). As simple as possible!
I have spent many days researching this and haven't come up with a clear path to proceed.
(Every tutorial and article I found assumed a single project.)
How do we structure the application to accomplish this?
How do we break up the application into separate projects/assemblies to do this?
Can you build a base project that contains the Master Page, authentication, and Global routing,
and then reference this in each of the potentially hundreds of other projects for each of the modules?
In development, does each sub-project need to contain the entire base project, or just the shared views folder, Global routing,
and web.config and a reference to the base project dll?
Any detail documents explaining this approach?
Any development/Testing issues?
Thanks for all input, we have to get this going soon.
Update:
Followed the example here link text
It is a great starting point!
I think this is exactly the case where DLR would help. Your Controllers and Views can be stored as scripts in the database. It will be very easy to deliver your application as a set of "small functional pieces". You could start from reading Haacked - Scripting ASP.NET MVC Views Stored In The Database
Absolutely, break the project up into sub-projects / modules containing your controllers. You can use an IoC container like Unity, Spring.Net, or Castle Windsor to locate your appropriate controllers in the child projects.
Implement your own IControllerFactory to do the Controller lookups in the IoC container based on the controller name passed to it. You're looking to put in place an IControllerFactory.CreateController method that looks something like:
public IController CreateController(RequestContext requestContext, string controllerName)
{
return (IController)IoCContainer.GetObjectByName(controllerName);
}
Then you should be able to simply modify your IoC configuration file to define your new controllers as they are deployed.
Google for MVC with MEF. There is an example by one of the MEF team that will suit your needs exactly.

Resources