Using Microsoft.Extension.DependencyInjection in Asp.net Web Api2 - dependency-injection

I am trying to implement Asp.Net webApi project which is depending on a third-party framework that does a lot of stuff with HttpContext.Current which does not exists in Asp.net Core. That is why I could not create Asp.net Core Web Application targeting .net full framework.
So I created old-school Asp.net Web Application project with WebApi extension.
Now I am trying to use Microsoft.Extension.DependencyInjection framework with it.
I found this example for Asp.Net Mvc4 but my project is WebApi. That approach did not work. Can anyone provide link or code snippet for me to move forward?
P.S: When providing an example, please make sure it should not use OWIN framework. Because when I tried to use OWIN pipeline, the third-party library(closed source) is not working properly.

I also found that example a while ago, i make it work perfect both in
Asp.Net Mvc4 and WebApi2 project.
Use some IoC container (eg. Unity, Autofac) for WebApi project, the most important thing is implementing the interface IDependencyResolver to make your own dependency resolver.
Hers's my code snippet for WebApi project.
WebApiConfig
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
...
// using Microsoft.Extension.DependencyInjection here.
Startup.Bootstrapper(config);
}
}
Startup
public class Startup
{
public static void Bootstrapper(HttpConfiguration config)
{
var provider = Configuration();
var resolver = new DefaultDependencyResolver(provider);
config.DependencyResolver = resolver;
}
private static IServiceProvider Configuration()
{
var services = new ServiceCollection();
services.AddControllersAsServices(typeof(Startup).Assembly.GetExportedTypes()
.Where(t => !t.IsAbstract && !t.IsGenericTypeDefinition)
.Where(t => typeof(IHttpController).IsAssignableFrom(t)
|| t.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)));
var serviceProvider = services.BuildServiceProvider();
return serviceProvider;
}
}
DefaultDependencyResolver
public class DefaultDependencyResolver : IDependencyResolver
{
private IServiceScope serviceScope;
protected IServiceProvider ServiceProvider { get; set; }
public DefaultDependencyResolver(IServiceProvider serviceProvider)
{
this.ServiceProvider = serviceProvider;
}
public object GetService(Type serviceType)
{
return this.ServiceProvider.GetService(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return this.ServiceProvider.GetServices(serviceType);
}
public IDependencyScope BeginScope()
{
serviceScope = this.ServiceProvider.CreateScope();
return new DefaultDependencyResolver(serviceScope.ServiceProvider);
}
public void Dispose()
{
// you can implement this interface just when you use .net core 2.0
// this.ServiceProvider.Dispose();
//need to dispose the scope otherwise
//you'll get a memory leak
serviceScope?.Dispose();
}
}
ServiceProviderExtensions
public static class ServiceProviderExtensions
{
public static IServiceCollection AddControllersAsServices(this IServiceCollection services,
IEnumerable<Type> controllerTypes)
{
foreach (var type in controllerTypes)
{
services.AddTransient(type);
}
return services;
}
}

Related

Unable to resolve service for type 'Core.Data.CoreContext' while attempting to activate 'Core.Data.Repositories.UnitOfWork'

I have part of WebAPI application that I want to move to separate project as class library.
It is common base structure that almost every app has so idea is to make it easy shareable.
Application type is:
ASP.NET Core Web Application / .NET Framework - ASP.NET Core 2.0 / Web API
What I have done in that direction is created a project named Core and moved those shared elements there, including Base Entities (e.g. User, Settings, etc), CoreContext, UnitOfWork, Generic Repository, BaseRepositories,...
In the Main project of app there are others Entities, AppContext that inherits CoreContext, more Repositories, and all Controllers, ...
I was able to build the app but when starting it get the following error:
InvalidOperationException: Unable to resolve service for type 'Core.Data.CoreContext' while attempting to activate 'Core.Data.Repositories.UnitOfWork'.
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type
serviceType, Type implementationType, ISet callSiteChain,
ParameterInfo[] parameters, bool throwIfCallSiteNotFound)...
Problem seems to be that UnitOfWork class is in Core project and in Main project is Startup.cs with method ConfigureServices that has services.AddTransient<IUnitOfWork, UnitOfWork>();.
Is this a bug or am I just not configuring it correctly and how could it be achieved, if possible at all?
*Further technical details:
NetCore & EF Core version: 2.0
Database Provider: Microsoft.EntityFrameworkCore.SqlServer
IDE: Visual Studio 2017 15.3
Operating system: Windows 10
UPDATE: Code Sample
namespace Main
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args).UseStartup<Startup>().Build();
}
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IUnitOfWork, UnitOfWork>();
services.AddMvc();
var conn = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<AppContext>(options => options.UseSqlServer(conn));
}
}
}
namespace Main.Data
{
public class AppContext : CoreContext
{
...
}
}
-
namespace Core.Data
{
public class UnitOfWork : IUnitOfWork, IDisposable
{
public CoreContext context;
public UnitOfWork(CoreContext context)
{
this.context = context;
}
public T Get<T>() where T : BaseRepository, new()
{
var repository = new T();
repository.Init(context);
return repository;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
public class UnitOfWork<TContext> : IUnitOfWork, IDisposable
where TContext : CoreContext
{
public UnitOfWork(TContext ctx) { ... }
...
}
-
public class AppUnitOfWork : UnitOfWork<AppContext> {
public AppUnitOfWork(AppContext ctx) : base(ctx) { }
}
...
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
...
services.AddTransient<IUnitOfWork, AppUnitOfWork>(); // Note the App prefix
services.AddDbContext<AppContext>(options => options.UseSqlServer(conn)); // Note the App prefix
}
...
}
Solution is from GitHub issue:

Register classes with primitive dependencies in ASP NET Core

I got baffled on how can i resolve connection string dependency on UserRepo once it is injected on an mvc controller by ASP NET Core's DI? Note that my repo is targeting NET 4.6. and uses either sql db with dapper orm. Tips and advice will do.
Heres the code.
Interface to be depended
public interface IUserRepo
{
List<User> GetAll();
}
Concrete class that will be injected to mvc controller and has its own dependency
public class UserRepo: IUserRepo
{
private string connectionString = "";
//Depends on a connectionstring
public UserRepo(string connectionString)
{
this.connectionString = connectionString;
}
public List<User> GetAll()
{
//create an sqlconnection using provided connectionstring
//return list from db...
}
}
on ASP MVC CORE's startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
//inject UserRepo , how to resolve UserRepo's dependency?
services.AddScoped<IUserRepo, UserRepo>();
}
You should use the AddScoped overload that accepts a delegate:
services.AddScoped<IAccountRepo>(c => new AccountRepo("constr"));
I suggest you using configuration based on ASP.NET Core documentation
If you have configuration setting (appsettings.json) like this:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplication1-26e8893e-d7c0-4fc6-8aab-29b59971d622;Trusted_Connection=True;MultipleActiveResultSets=true"
},
}
And your Startup.cs:
private readonly IConfigurationRoot _configuration;
public Startup(IHostingEnvironment env)
{
_configuration = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile($"appsettings.json", optional:false, reloadOnChange:true)
.Build();
}
public void ConfigureServices(IServiceCollection services)
{
...
services.AddSingleton<IConfiguration>(provider => _configuration);
...
}
Then you can resolve it on the UserRepo easily:
public class UserRepo: IUserRepo
{
private readonly string connectionString;
public UserRepo(IConfiguration configuration)
{
this.connectionString = configuration.GetConnectionString("DefaultConnection");;
}
public List<User> GetAll()
{
//create an sqlconnection using provided connectionstring
//return list from db...
}
}

How to use session values with Unity and DependencyResolver

I'm using MVC4 and Unity 2.1. My services require a service key based on credentials retrieved from session state.
I register my service(s) like so:
container.RegisterType<IInventoryService, InventoryService>();
The constructor for InventoryService is equally simple:
public InventoryService(ServiceKey serviceKey) { ... }
In my website when I've needed a service I use a service locator that automatically composes the service key using credentials from session.
public static T Resolve<T>(ServiceKey serviceKey = null)
{
if (serviceKey == null)
{
serviceKey = SessionManager.ServiceKey;
}
var parameterOverride = new ParameterOverride(SERVICEKEY_PARAMETERNAME, serviceKey);
return Resolve<T>(null, parameterOverride);
}
This has worked well. The problem is that I'm now converting my site to MVC and attempting to inject services into controllers using a simple dependency resolver that uses my exiting service locator (dependency factory):
public class CustomDependencyResolver : IDependencyResolver
{
public object GetService(Type serviceType)
{
return MvcDependencyFactory.Resolve(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return MvcDependencyFactory.ResolveAll(serviceType);
}
}
My controller looks like:
public InventoryController(IInventoryService inventoryService) { ... }
The problem is that MVC still complains about not finding a parameterless constructor when trying to instantiate the inventory controller. I think this is because I haven't registered a service key in Unity. But if I try doing so, I find that MVC is trying to resolve the controllers, and subsequently the services, before session has even been constructed.
Am I not thinking about this correctly? Each step feels pretty reasonable -- using session credentials in a service, using a service in a controller, using a resolver to help build the controller -- but I've been beating my head against the wall getting this to work.
You can use the InjectionFactory in Unity (Microsoft.Practices.Unity.InjectionFactory) to specify a function to handle the resolution of your dependency. This function will only be executed when the dependency is resolved. In the below example, "c" is your Unity container passed as a argument so that you can do additional resolves within your function.
replace:
container.RegisterType<IInventoryService, InventoryService>();
with:
container.RegisterType<IInventoryService>(new InjectionFactory(c =>
new InventoryService(SessionManager.ServiceKey)));
Using the Unity.Mvc4 package seemed to fix the problem, though it's not clear to me why. But rather than use yet another package and hide away my questions, I decided to add a parameterless constructor that manually resolves itself as necessary:
public InventoryController() : this (MvcDependencyFactory.Resolve<IInventoryService>(SessionManger.ServiceKey) { }
It still allows for unit testing of the controllers (via injection) while being transparent about where the resolution is happening when the parameterless constructor is called.
Below is a custom IDependencyResolver, which was fairly straight forward once I started to dig into how it worked and differed from IoC container resolution. You need the try/catches to capture MVC's attempted resolution of IControllerActivator (source: http://www.devtrends.co.uk/blog/do-not-implement-icontrolleractivator-in-asp.net-mvc-3). If IControllerActivator cannot be resolved, your custom IDependencyResolver will be queried for your controller instead (which will use your IoC container of choice).
I added the below class to my basic MVC4's App_Start folder:
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Microsoft.Practices.Unity;
using Sample.Web.Controllers;
namespace Sample.Web.App_Start
{
public static class UnityConfig
{
public static void ConfigureContainer()
{
IUnityContainer container = BuildUnityContainer();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer();
container.RegisterType<IHomeService>(new InjectionFactory( c =>
new HomeService("this string is a dependency.")));
container.RegisterType<IController, HomeController>("Home");
return container;
}
}
public class UnityDependencyResolver : IDependencyResolver
{
private readonly IUnityContainer _container;
public UnityDependencyResolver(IUnityContainer container)
{
_container = container;
}
public object GetService(Type serviceType)
{
try
{
return _container.Resolve(serviceType);
}
catch (ResolutionFailedException)
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
try
{
return _container.ResolveAll(serviceType);
}
catch (ResolutionFailedException)
{
return new List<object>();
}
}
}
}
Here is my simple controller:
using System.Web.Mvc;
namespace Sample.Web.Controllers
{
public class HomeController : Controller
{
private readonly IHomeService _service;
public HomeController(IHomeService service)
{
_service = service;
}
public ActionResult Index()
{
ViewBag.SomeData = _service.GetSomeData();
return View();
}
}
public interface IHomeService
{
string GetSomeData();
}
public class HomeService : IHomeService
{
private readonly string _data;
public HomeService(string data)
{
_data = data;
}
public string GetSomeData()
{
return _data;
}
}
}
Here is my epically huge view:
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>#ViewBag.SomeData</p>

asp.net mvc autofac registery and resolver

I am working on ASP.NET MVC 3 application. I am using Autofac as my dependency resolver.
I have two projects one core and other UI. In the core project I have an interface which holds
information about the logged in user if any. This is inherited in my UI project.
public interface IWebContext
{
User User {get;set}
bool IsLoggedIn {get;}
}
In ui project this is implemented as
public class WebContext : IWebContext
{
//codes here to get user and islogged in proerty.
}
In the core project I am creating link based on some logic.
public static class ButtonExtension
{
public static MvcHtmlString EditButton(this HtmlHelper helper, string controller, string action, object id, string text)
{
var webContext= how to get IWebContext here.
if (!webContext.IsLoggedIn)
{
return MvcHtmlString.Empty;
}
return MvcHtmlString.Create(string.Format("{3}", controller, action, id, text));
}
}
In my global.asax I am registering all my services using IOC static class
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
IOC.Build();
}
here is my IOC class.
public static class IOC
{
private static IContainer _container;
public static void Build()
{
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.Register(c => new WebContext()).As<IWebContext>().SingleInstance();
builder.Register(c => new ImageServiceLocal()).As<IImageService>().InstancePerHttpRequest();
builder.RegisterFilterProvider();
_container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(_container));
}
public static T Resolve<T>()
{
if (_container == null)
Build();
return _container.Resolve<T>();
}
}
var webContext = DependencyResolver.Current.GetRequestLifetimeScope()
.Resolve<IWebContext>();

Castle Windsor IoC in an MVC application

Prepare for a wall of code... It's a long read, but it's as verbose as I can get.
In response to Still lost on Repositories and Decoupling, ASP.NET MVC
I think I am starting to get closer to understanding this all.
I'm trying to get used to using this. Here is what I have so far.
Project
Project.Web (ASP.NET MVC 3.0 RC)
Uses Project.Models
Uses Project.Persistence
Project
Project.Models (Domain Objects)
Membership.Member
Membership.IMembershipProvider
Project
Project.Persistence (Fluent nHibernate)
Uses Project.Models
Uses Castle.Core
Uses Castle.Windsor
Membership.MembershipProvider : IMembershipProvider
I have the following class in Project.Persistence
using Castle.Windsor;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
namespace Project.Persistence
{
public static class IoC
{
private static IWindsorContainer _container;
public static void Initialize()
{
_container = new WindsorContainer()
.Install(
new Persistence.Containers.Installers.RepositoryInstaller()
);
}
public static T Resolve<T>()
{
return _container.Resolve<T>();
}
}
}
namespace Persistence.Containers.Installers
{
public class RepositoryInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(
Component
.For<Membership.IMembershipProvider>()
.ImplementedBy<Membership.MembershipProvider>()
.LifeStyle.Singleton
);
}
}
}
Now, in Project.Web Global.asax Application_Start, I have the following code.
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
// Register the Windsor Container
Project.Persistence.IoC.Initialize();
}
Now then, in Project.Web.Controllers.MembershipController I have the following code.
[HttpPost]
public ActionResult Register( Web.Models.Authentication.Registration model)
{
if (ModelState.IsValid)
{
var provider = IoC.Resolve<Membership.IMembershipProvider>();
provider.CreateUser(model.Email, model.Password);
}
// If we got this far, something failed, redisplay form
return View(model);
}
So I am asking first of all..
Am I on the right track?
How can I use Castle.Windsor for my ISessionFactory
I have my SessionFactory working like this ...
namespace Project.Persistence.Factories
{
public sealed class SessionFactoryContainer
{
private static readonly ISessionFactory _instance = CreateSessionFactory();
static SessionFactoryContainer()
{
}
public static ISessionFactory Instance
{
get { return _instance; }
}
private static ISessionFactory CreateSessionFactory()
{
return Persistence.SessionFactory.Map(#"Data Source=.\SQLEXPRESS;Initial Catalog=FluentExample;Integrated Security=true", true);
}
}
}
namespace Project.Persistence
{
public static class SessionFactory
{
public static ISessionFactory Map(string connectionString, bool createSchema)
{
return FluentNHibernate.Cfg.Fluently.Configure()
.Database(FluentNHibernate.Cfg.Db.MsSqlConfiguration.MsSql2008
.ConnectionString(c => c.Is(connectionString)))
.ExposeConfiguration(config =>
{
new NHibernate.Tool.hbm2ddl.SchemaExport(config)
.SetOutputFile("Output.sql")
.Create(/* Output to console */ false, /* Execute script against database */ createSchema);
})
.Mappings(m =>
{
m.FluentMappings.Conventions.Setup(x =>
{
x.AddFromAssemblyOf<Program>();
x.Add(FluentNHibernate.Conventions.Helpers.AutoImport.Never());
});
m.FluentMappings.AddFromAssemblyOf<Mapping.MembershipMap>();
}).BuildSessionFactory();
}
So basically, within my Project.Persistence layer, I call the SessionFactory like this..
var session = SessionFactoryContainer.Instance.OpenSession()
Am I even getting close to doing this right? I'm still confused - I feel like the ISessionFactory should be part of Castle.Windsor, but I can't seem to figure out how to do that. I'm confused also about the way I am creating the Repository in the Controller. Does this mean I have to do all of the 'mapping' each time I use the Repository? That seems like it would be very resource intensive.
Firstly some conceptual details. In an ASP.NET MVC application the typical entry point for a page request is a controller. We want the Inversion of Control container to resolve our controllers for us, because then any dependencies that the controllers have can also be automatically resolved simply by listing the dependencies as arguments in the controllers' constructors.
Confused yet? Here's an example of how you'd use IoC, after it is all set up. I think explaining it this way makes things easier!
public class HomeController : Controller
{
// lets say your home page controller depends upon two providers
private readonly IMembershipProvider membershipProvider;
private readonly IBlogProvider blogProvider;
// constructor, with the dependencies being passed in as arguments
public HomeController(
IMembershipProvider membershipProvider,
IBlogProvider blogProvider)
{
this.membershipProvider = membershipProvider;
this.blogProvider = blogProvider;
}
// so taking your Registration example...
[HttpPost]
public ActionResult Register( Web.Models.Authentication.Registration model)
{
if (ModelState.IsValid)
{
this.membershipProvider.CreateUser(model.Email, model.Password);
}
// If we got this far, something failed, redisplay form
return View(model);
}
}
Note that you have not had to do any resolving yourself, you have just specified in the controller what the dependencies are. Nor have you actually given any indication of how the dependencies are implemented - it's all decoupled. It's very simple there is nothing complicated here :-)
Hopefully at this point you are asking, "but how does the constructor get instantiated?" This is where we start to set up your Castle container, and we do this entirely in the MVC Web project (not Persistence or Domain). Edit the Global.asax file, setting Castle Windsor to act as the controller factory:
protected void Application_Start()
{
//...
ControllerBuilder.Current
.SetControllerFactory(typeof(WindsorControllerFactory));
}
...and define the WindsorControllerFactory so that your controllers are instantiated by Windsor:
/// Use Castle Windsor to create controllers and provide DI
public class WindsorControllerFactory : DefaultControllerFactory
{
private readonly IWindsorContainer container;
public WindsorControllerFactory()
{
container = ContainerFactory.Current();
}
protected override IController GetControllerInstance(
RequestContext requestContext,
Type controllerType)
{
return (IController)container.Resolve(controllerType);
}
}
The ContainerFactory.Current() method is static singleton that returns a configured Castle Windsor container. The configuration of the container instructs Windsor on how to resolve your application's dependencies. So for example, you might have a container configured to resolve the NHibernate SessionFactory, and your IMembershipProvider.
I like to configure my Castle container using several "installers". Each installer is responsible for a different type of dependency, so I'd have a Controller installer, an NHibernate installer, a Provider installer for example.
Firstly we have the ContainerFactory:
public class ContainerFactory
{
private static IWindsorContainer container;
private static readonly object SyncObject = new object();
public static IWindsorContainer Current()
{
if (container == null)
{
lock (SyncObject)
{
if (container == null)
{
container = new WindsorContainer();
container.Install(new ControllerInstaller());
container.Install(new NHibernateInstaller());
container.Install(new ProviderInstaller());
}
}
}
return container;
}
}
...and then we need each of the installers. The ControllerInstaller first:
public class ControllerInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(
AllTypes
.FromAssembly(Assembly.GetExecutingAssembly())
.BasedOn<IController>()
.Configure(c => c.Named(
c.Implementation.Name.ToLowerInvariant()).LifeStyle.PerWebRequest));
}
}
... and here is my NHibernateInstaller although it is different to yours, you can use your own configuration. Note that I'm reusing the same ISessionFactory instance every time one is resolved:
public class NHibernateInstaller : IWindsorInstaller
{
private static ISessionFactory factory;
private static readonly object SyncObject = new object();
public void Install(IWindsorContainer container, IConfigurationStore store)
{
var windsorContainer = container.Register(
Component.For<ISessionFactory>()
.UsingFactoryMethod(SessionFactoryFactory));
}
private static ISessionFactory SessionFactoryFactory()
{
if (factory == null)
{
lock (SyncObject)
{
if (factory == null)
{
var cfg = new Configuration();
factory = cfg.Configure().BuildSessionFactory();
}
}
}
return factory;
}
}
And finally you'll want to define your ProvidersInstaller:
public class ProvidersInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
var windsorContainer = container
.Register(
Component
.For<IMembershipProvider>()
.ImplementedBy<SubjectQueries>())
.Register(
Component
.For<IBlogProvider>()
.ImplementedBy<SubjectQueries>());
// ... and any more that your need to register
}
}
This should be enough code to get going! Hopefully you're still with me as the beauty of the Castle container becomes apparent very shortly.
When you define your implementation of your IMembershipProvider in your persistence layer, remember that it has a dependency on the NHibernate ISessionFactory. All you need to do is this:
public class NHMembershipProvider : IMembershipProvider
{
private readonly ISessionFactory sessionFactory;
public NHMembershipProvider(ISessionFactory sessionFactory)
{
this.sessionFactory = sessionFactory;
}
}
Note that because Castle Windsor is creating your controllers and the providers passed to your controller constructor, the provider is automatically being passed the ISessionFactory implementation configured in your Windsor container!
You never have to worry about instantiating any dependencies again. Your container does it all automatically for you.
Finally, note that the IMembershipProvider should be defined as part of your domain, as it is defining the interface for how your domain behaviours. As noted above, the implementation of your domain interfaces which deal with databases are added to the persistence layer.
Avoid using a static IoC class like this. By doing this you're using the container as a service locator, so you won't achieve the full decoupling of inversion of control. See this article for further explanations about this.
Also check out Sharp Architecture, which has best practices for ASP.NET MVC, NHibernate and Windsor.
If you have doubts about the lifecycle of the container itself, see Usage of IoC Containers; specifically Windsor

Resources