We are using Caliburn.Micro for our MVVM framework, StructureMap for our IoC container, and MediatR for our mediator implementation. This is all working fine, except the recommended way to register the MediatR event handlers doesn't play nicely with Caliburn.Micro's recommended approach with using the ViewModels as their own handlers.
Caliburn.Micro implements the mediator pattern via the EventAggregator, which requires that you inject the IEventAggregator into your ViewModel and Subscribe to itself (or something implements the IHandle<> interface). MediatR takes a more decoupled approach, recommending you reflectively scan assemblies for types that close the IRequestHandler<,> and other types.
I believe it's my lack of experience with StructureMap that is my issue.
What I'd like to do is be able to implement the Handler functionality on the ViewModels themselves (like Caliburn.Micro suggests) but also ensure the ViewModels are registered as Singletons for Caliburn.Micro.
public class RibbonMenuViewModel : PropertyChangedBase, INotificationHandler<SomethingSelectedEvent> { }
When StructureMap processes the following Registry, there will be 2 instances of RibbonMenuViewModel: one singleton version for Caliburn.Micro and one transient version that closes the MediatR INotificationHandler<> generic type.
StructureMap Registry
public class ViewModelsRegistry : Registry
{
public ViewModelsRegistry()
{
// ensure registration for the ViewModel for Caliburn.Micro
this.ForConcreteType<RibbonMenuViewModel>().Configure.Singleton();
// MediatR handler registrations
this.Scan(s =>
{
s.Assembly(this.GetType().Assembly);
s.ConnectImplementationsToTypesClosing(typeof (IRequestHandler<,>));
s.ConnectImplementationsToTypesClosing(typeof (IAsyncRequestHandler<,>));
s.ConnectImplementationsToTypesClosing(typeof (INotificationHandler<>));
s.ConnectImplementationsToTypesClosing(typeof (IAsyncNotificationHandler<>));
});
}
}
I would like advice on the best way to use the Singleton ViewModel registration as the INotificationHandler instance for MediatR
Here is the Caliburn.Micro configuration for reference:
Caliburn Bootstrapper Configuration
protected override void Configure()
{
this.configureTypeMappings();
if (!Execute.InDesignMode)
{
this.configureIocContainer();
}
}
private void configureIocContainer()
{
this.container = new Container(this.getStructureMapConfig);
}
private void getStructureMapConfig(ConfigurationExpression cfg)
{
cfg.For<IWindowManager>().Use<WindowManager>().Singleton();
cfg.Scan(s =>
{
s.AssemblyContainingType<ViewModelsRegistry>();
s.LookForRegistries();
});
}
protected override IEnumerable<object> GetAllInstances(Type serviceType)
{
return this.container.GetAllInstances(serviceType).OfType<object>();
}
protected override object GetInstance(Type serviceType, string key)
{
if (serviceType == null) serviceType = typeof(object);
var returnValue = key == null
? this.container.GetInstance(serviceType) : this.container.GetInstance(serviceType, key);
return returnValue;
}
protected override void BuildUp(object instance) { this.container.BuildUp(instance); }
I had a similar problem.
Here is how I fixed it.
public class ViewModelsRegistry : Registry
{
public ViewModelsRegistry()
{
// MediatR handler registrations
this.Scan(s =>
{
s.Assembly(this.GetType().Assembly);
s.ConnectImplementationsToTypesClosing(typeof (IRequestHandler<,>));
s.ConnectImplementationsToTypesClosing(typeof (IAsyncRequestHandler<,>));
s.ConnectImplementationsToTypesClosing(typeof (INotificationHandler<>));
s.ConnectImplementationsToTypesClosing(typeof (IAsyncNotificationHandler<>));
s.ExcludeType<RibbonMenuViewModel>();
});
// ensure registration for the ViewModel for Caliburn.Micro
For(typeof(INotificationHandler<>)).Singleton().Add(typeof(RibbonMenuViewModel));
}
}
I hope this helps.
Related
I'm developing an asp.net core 3.1 webapi application and i'm using Autofac as DI container.
For one particular case i cannot use ConstructorInjection nor propertyinjection nor methodinjection. My only way is to implement a sort of ServiceLocator pattern with the support of Autofac.
*I known that the service locator is an antipattern, but i will use that only if it will be the only chance *
Said that, I create a little static class :
public static class ServiceLocator
{
private static XXXX Resolver;
public static T Resolve<T>()
{
return Resolver.Resolve<T>();
}
public static void SetCurrentResolver(XXXX resolver)
{
Resolver = resolver;
}
}
I write XXXX on the type of Resolver property because i don't know which is the Autofac class to use. The method SetCurrentResolver will be called in the Configure method of Startup.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILifetimeScope serviceProvider)
{
//OTHER STUFF NOT RELATED HERE
ServiceLocator.SetCurrentResolver(serviceProvider);
}
I tried to pass the instance of ILifetimeScope but when i use it later in the service locator it will be Disposed and then not work. I thinked to pass an IContainer object but i'm not able to retrieve an instance in Startup.cs (neither in the Configure method nor in the ConfigureContainer)
I Report the ConfigureContainer method for completion
public void ConfigureContainer(ContainerBuilder builder)
{
//first register the dependency for WebApi Project
builder.RegisterType<HttpContextUserService>().As<IUserService>().SingleInstance();
//and then register the dependency for all other project
var appConfiguration = new AppConfiguration();
Configuration.GetSection("Application").Bind(appConfiguration);
builder.RegisterInstance(appConfiguration).SingleInstance();
builder.RegisterModule(new DependencyInjectionBootstrapper(appConfiguration));
}
Anyone can help me with this problem?
Thanks
This is actually answered in the Autofac docs if you look at the example.
Here are the relevant bits.
public class Startup
{
public Startup(IHostingEnvironment env)
{
// Body omitted for brevity.
}
public ILifetimeScope AutofacContainer { get; private set; }
public void ConfigureServices(IServiceCollection services)
{
// Body omitted for brevity.
}
public void ConfigureContainer(ContainerBuilder builder)
{
// Body omitted for brevity.
}
public void Configure(IApplicationBuilder app)
{
// If, for some reason, you need a reference to the built container, you
// can use the convenience extension method GetAutofacRoot.
// THIS IS WHERE YOU'D SET YOUR SERVICE LOCATOR.
this.AutofacContainer = app.ApplicationServices.GetAutofacRoot();
}
}
When there are multiple named implementations for a given interface, how does the container (I am using Unity in a Prism application) know which one to inject unless I call the container.Resolve with the registered name? Here is a simple example:
public interface IDependencyClass
{
void DoSomething();
}
public class DependencyClassA : IDependencyClass
{
void DoSomething() { }
}
public class DependencyClassB : IDependencyClass
{
void DoSomething() { }
}
public interface IConsumer
{
void TakeUserSpecificAction();
}
public class Consumer : IConsumer
{
IDependencyClass dependencyInstance;
public Consumer(IDependencyClass _dependencyInstance)
{
dependencyInstance = _dependencyInstance;
}
public void TakeUserSpecificAction()
{
dependencyInstance.DoSomething();
}
}
public class MyBootStrapper : UnityBootstrapper
{
protected override void ConfigureContainer()
{
base.ConfigureContainer();
Container.RegisterType<IDependencyClass, DependencyClassA>( "InstanceA" );
Container.RegisterType<IDependencyClass, DependencyClassB>( "InstanceB" );
Container.RegisterType<IConsumer, Consumer>();
}
}
and here is my MainViewModel from my application. The "RaiseSomeCommand" command is not enabled until the user has logged in. When it is enabled, it can execute the ReaiseConsumerCommandRequest, which in turn calls the consumer. Here is my ViewModel.
public class MainWindowViewModel
{
private readonly IRegionManager regionManager;
private readonly ILoginService loginService;
private readonly IConsumer consumer;
public ICommand RaiseSomeCommand { get; set; }
public MainWindowViewModel( IRegionManager regMgr, ILoginService _loginService, IConsumer _consumer )
{
regionManager = regMgr;
loginService = _loginService;
consumer = _consumer;
NavigateCommand = new DelegateCommand<string>( Navigate );
LoginViewRequest = new InteractionRequest<INotification>();
RaiseSomeCommand = new DelegateCommand( RaiseConsumerCommandRequest );
}
private void RaiseConsumerCommandRequest()
{
consumer.TakeUserSpecificAction();
}
}
So, when I execute
consumer.TakeUserSpecificAction();
which DependencyClass instance am I using? DependencyClassA or DependencyClassB. Also, If I want to use specifically say DependencyClassB, What do I need to do to make it happen. I don't want to call
container.Reslove<IDependencyClass>("InstanceB")
in my ViewModel because I am then using the container as a service locator. I am also passing the container reference around.
I have seen in some code examples that the constructor parameter for the consumer class is decorated with a Dependency attribute like below.
public class Consumer
{
IDependencyClass dependencyInstance;
public Consumer([Dependency("InstanceB")]IDependencyClass _dependencyInstance)
{
dependencyInstance = _dependencyInstance;
}
}
But then, I am putting a hard constraint on the Consumer to use only the "InstanceB" implementation. Secondly, I am creating a dependency to Unity. Thirdly, now I have to clone the Consumer class to use "InstanceA" Implementation. That goes against the DRY principle.
I have heard that these conditions are application decisions and not an IoC related logic. I can agree with that argument. But then, where and how in the application would I resolve the right implementation without violating one rule or another?
I can't see how I can inject the right concrete instance unless I choose to use one of the above two options. Container.Resolve or Dependency attribute. Can anybody help please?
I am trying to boot strap nancyfx with structuremap bootstrapper
https://github.com/NancyFx/Nancy.Bootstrappers.StructureMap
Here is my setup:
protected override void ConfigureApplicationContainer(IContainer container)
{
container.Configure(x =>
{
x.ForSingletonOf<IRazorConfiguration>()
.Use<DefaultRazorConfiguration>();
x.ForSingletonOf<ISessionContainer>().Use<SessionContainer>();
x.For<IRepository>().LifecycleIs(new HttpContextLifecycle()).Use<Repository>();
x.Scan(scanner=>
{
scanner.TheCallingAssembly();
scanner.AddAllTypesOf<IRepository>();
});
});
base.ConfigureApplicationContainer(container);
}
public interface IRepository
{
void Save();
}
public class Repository:IRepository
{
ISessionContainer _session;
public Repository(ISessionContainer container)
{
_session = container;
}
public void Save()
{
}
}
When I use var repo = ObjectFactory.GetInstance<IRepository>();, I get this exception:
StructureMap Exception Code: 202
No Default Instance defined for PluginFamily Infrastructure.IRepository, Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
I'd like to help you get rid of the hack... the source of your problem is the way you are using ObjectFactory. Really you shouldn't be using ObjectFactory to "GetInstance" inside your NancyModule. Instead, you should include IRepository in the constructor of the NancyModule where the repository is needed. Then, Structuremap (which has been wired into the Nancy framework using your bootstrapper) will simple inject the concrete repository into your module when it is instantiated. Here's an example of a NancyModule:
public class ProductModule : NancyModule {
private IRepository _repository;
public ProductModule(IRepository repository) {
_repository = repository;
SetupRoutes();
}
private void SetupRoutes() {
Get["/product/{id}"] = p => {
return _repository.Get<Product>((int)p.id);
};
}
}
Here, the module isn't calling out to the IOC to get a repo... it's already got it. Your bootstrapper makes this possible. Now, you can get rid of the hacky configuration of ObjectFactory.
As some general advice, if you find yourself using "ObjectFactory" to resolve types, you should slap yourself and stop typing. Instead, you should inject the dependency using constructor injection like I show above.
Not sure what happened to the proposed answer, but here is how I ended up resolving this issue.
protected override void ConfigureApplicationContainer(IContainer container)
{
container.Configure(x =>
{
x.ForSingletonOf<IRazorConfiguration>()
.Use<DefaultRazorConfiguration>();
x.ForSingletonOf<ISessionContainer>().Use<SessionContainer>();//Duplicate
x.Scan(scanner=>
{
scanner.TheCallingAssembly();
scanner.AddAllTypesOf<IRepository>();
});
});
ObjectFactory.Configure(x =>
{
x.ForSingletonOf<ISessionContainer>().Use<SessionContainer>();//Duplicate
x.For<IRepository>().Use<Repository>();
});
base.ConfigureApplicationContainer(container);
}
It's a hack but this is the only way I managed to get this to work.
Simple question.
How do I use UnitOfWork with Castle.Windsor, nHibernate, and ASP.NET MVC?
Now for the extended details. In my quest to understand the UnitOfWork pattern, I'm having difficulty coming across anything that uses a direct example in conjunction with Castle.Windsor, specifically in regards to the way it needs to be installed.
Here is my understanding so far.
IUnitOfWork
The IUnitOfWork interface is used to declare the pattern
The UnitOfWork class must Commit and Rollback transactions, and Expose a Session.
So with that said, here is my IUnitOfWork. (I am using Fluent nHibernate)
public interface IUnitOfWork : IDisposable
{
ISession Session { get; private set; }
void Rollback();
void Commit();
}
So here is my Castle.Windsor Container Bootstrapper (ASP.NET MVC)
public class WindsorContainerFactory
{
private static Castle.Windsor.IWindsorContainer container;
private static readonly object SyncObject = new object();
public static Castle.Windsor.IWindsorContainer Current()
{
if (container == null)
{
lock (SyncObject)
{
if (container == null)
{
container = new Castle.Windsor.WindsorContainer();
container.Install(new Installers.SessionInstaller());
container.Install(new Installers.RepositoryInstaller());
container.Install(new Installers.ProviderInstaller());
container.Install(new Installers.ControllerInstaller());
}
}
}
return container;
}
}
So now, in my Global.asax file, I have the following...
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
// Register the Windsor Container
ControllerBuilder.Current
.SetControllerFactory(new Containers.WindsorControllerFactory());
}
Repository
Now I understand that I need to pass the ISession to my Repository. So then, let me assume IMembershipRepository.
class MembershipRepository : IMembershipRepository
{
private readonly ISession session;
public MembershipRepository(ISession session)
{
this.session = session;
}
public Member RetrieveMember(string email)
{
return session.Query<Member>().SingleOrDefault( i => i.Email == email );
}
}
So I am confused, now. Using this method, the ISession doesn't get destroyed properly, and the UnitOfWork never gets used.
I've been informed that UnitOfWork needs to go in the Web Request Level - but I cannot find anything explaining how to actually go about this. I do not use a ServiceLocator of any sort ( as when I tried, I was told this was also bad practice... ).
Confusion -- How does a UnitOfWork get created?
I just don't understand this, in
general. My thought was that I would
start passing UnitOfWork into the
Repository constructors - but if it
has to go in the Web Request, I'm not
understanding where the two relate.
Further Code
This is extra code for clarification, simply because I seem to have a habit of never providing the right information for my questions.
Installers
public class ControllerInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(
AllTypes.FromThisAssembly()
.BasedOn<IController>()
.Configure(c => c.LifeStyle.Transient));
}
}
public class ProviderInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(
Component
.For<Membership.IFormsAuthenticationProvider>()
.ImplementedBy<Membership.FormsAuthenticationProvider>()
.LifeStyle.Singleton
);
}
}
public class RepositoryInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(
Component
.For<Membership.IMembershipRepository>()
.ImplementedBy<Membership.MembershipRepository>()
.LifeStyle.Transient
);
container.Register(
Component
.For<Characters.ICharacterRepository>()
.ImplementedBy<Characters.CharacterRepository>()
.LifeStyle.Transient
);
}
}
public class SessionInstaller : Castle.MicroKernel.Registration.IWindsorInstaller
{
private static ISessionFactory factory;
private static readonly object SyncObject = new object();
public void Install(Castle.Windsor.IWindsorContainer container, IConfigurationStore store)
{
container.Register(
Component.For<ISessionFactory>()
.UsingFactoryMethod(SessionFactoryFactory)
.LifeStyle.Singleton
);
container.Register(
Component.For<ISession>()
.UsingFactoryMethod(c => SessionFactoryFactory().OpenSession())
.LifeStyle.Transient
);
}
private static ISessionFactory SessionFactoryFactory()
{
if (factory == null)
lock (SyncObject)
if (factory == null)
factory = Persistence.SessionFactory.Map(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["Remote"].ConnectionString);
return factory;
}
}
UnitOfWork
Here is my UnitOfWork class verbatim.
public class UnitOfWork : IUnitOfWork
{
private readonly ISessionFactory sessionFactory;
private readonly ITransaction transaction;
public UnitOfWork(ISessionFactory sessionFactory)
{
this.sessionFactory = sessionFactory;
Session = this.sessionFactory.OpenSession();
transaction = Session.BeginTransaction();
}
public ISession Session { get; private set; }
public void Dispose()
{
Session.Close();
Session = null;
}
public void Rollback()
{
if (transaction.IsActive)
transaction.Rollback();
}
public void Commit()
{
if (transaction.IsActive)
transaction.Commit();
}
}
Your NH Session is a Unit of Work already http://nhforge.org/wikis/patternsandpractices/nhibernate-and-the-unit-of-work-pattern.aspx
So I'm not sure why you would ever need to abstract this out any further. (if anyone reading this answer know's why I would be happy to hear, I've honestly never heard of any reason why you would need to...)
I would implement a simple Session Per Request. I don't know how you would do that with Windsor since I've never used it, but with It's rather simple with StructureMap.
I wrap the structuremap factory to hold my session factory and inject the session into the repositories as required.
public static class IoC
{
static IoC()
{
ObjectFactory.Initialize(x =>
{
x.UseDefaultStructureMapConfigFile = false;
// NHibernate ISessionFactory
x.ForSingletonOf<ISessionFactory>()
.Use(new SessionFactoryManager().CreateSessionFactory());
// NHibernate ISession
x.For().HybridHttpOrThreadLocalScoped()
.Use(s => s.GetInstance<ISessionFactory>().OpenSession());
x.Scan(s => s.AssembliesFromApplicationBaseDirectory());
});
ObjectFactory.AssertConfigurationIsValid();
}
public static T Resolve<T>()
{
return ObjectFactory.GetInstance<T>();
}
public static void ReleaseAndDisposeAllHttpScopedObjects()
{
ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects();
}
}
In the global.asax file on Request_End I call the ReleaseAndDisposeAllHttpScopedObjects() method.
protected void Application_EndRequest(object sender, EventArgs e)
{
IoC.ReleaseAndDisposeAllHttpScopedObjects();
}
So the session is opened when I call my first repository, and when the request is ended it's disposed of. The repositories have a constructor which takes ISession and assigns it to a property. Then I just resolve the repo like:
var productRepository = IoC.Resolve<IProductRepository>();
Hope that helps. There are many other ways of doing it, this is what works for me.
Is it a linguistic/impedence mismatch issue that the library terms don't jive with the lingo you are familiar with?
I am pretty new to this [fluent] nhibernate, too, so I am still trying to figure it out, but my take is this:
Normally, associate the ISession with an Application session (eg, if it were a web app, you would might consider associating the creation of the session with the Application_Start event, and dispose when the app shuts down -- gracefully or not). When the scope of the app goes away, so should the repository.
The UnitOfWork is just a way of wrapping/abstraction transactions, where you have more than one action to perform during an update, and to remain consistent they must both complete, in sequence, and each successfully. Such as when applying more than trivial business rules to data creation, analysis, or transforms...
Here is a link to a blog post that provides an example of using ISession and UnitOfWork in a fluent style.
http://blog.bobcravens.com/2010/06/the-repository-pattern-with-linq-to-fluent-nhibernate-and-mysql/#comments
EDIT: Just to emphasize, I don't think you -must- use a unit of work for every operation against a repository. The UnitOfWork is only really needed when a transaction is the only reasonably choice, but I am just starting with this, too.
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