I have a question for the Ioc gurus out there.
I am working with a co-worker to wrap our minds around Castle Windsor IoC. We are having a difference of opinion about static Domain Service objects within asp.Net webforms. We have a static factory called BLServiceFactory in our Infrastructure layer that retrieves the container.
public sealed class BLServiceFactory
{
private static BLServiceFactory _instance = new BLServiceFactory();
IWindsorContainer _container = new WindsorContainer();
public static BLServiceFactory Instance
{
get
{return _instance;}
}
public T Create<T>()
{
return (T)_container[typeof(T)];
}
private BLServiceFactory()
{
_container.AddComponent("DataContext", typeof(DAL.DataContextFactory), typeof(DAL.CPContextFactory));
_container.AddComponent("Repository", typeof(DAL.IRepository<>), typeof(DAL.Repository<>));
_container.AddComponent("UserManager", typeof(BL.IUserManager), typeof(BL.UserManager));
_container.AddComponent("RoleService", typeof(BL.IRoleService), typeof(BL.RoleService));
}
}
We are pulling instances from the factory in our code behinds like this.
public partial class PrintList : System.Web.UI.Page
{
private static readonly ISchoolManager _schoolService = BLServiceFactory.Instance.Create<ISchoolManager>();
Models.TechSchool _tech;
protected void Page_Load(object sender, EventArgs e)
{
_tech = _schoolService.GetSchoolForTechPrep(Profile.UserName);
}
protected void DoOtherStuff...
{
_schoolService.Foo(_tech);
}
}
To me this looks like we will be serving up the same instance to every session. That would indeed be bad! My co-worker thinks that since all of our Domain Services are marked Transient, each page request will get a new instance.
I have also read a bit about memory leaks due to objects marked transient not released for garbage collection. Has this been addressed in the latest release of Castle Windsor, or should I be explicitly releasing objects? Of course as it stands now, all the objects are static and this would be irrelevant.
The BLServiceFactory is a service locator. I recommend using CommonServiceLocator instead of your own if you're going to use a service locator. Component registration does not belong inside the service locator.
Now, in the code you posted, there is no mention of those components being transient, unless you marked them with the [Transient] attribute. If you didn't, those components will be singletons, which is the default lifestyle in Windsor.
Since the variable _schoolService in PrintList is static, the same instance of ISchoolManager will be used for all requests to the PrintList page. If you really want it to be transient, remove the "static" keyword.
About releasing components, see this article.
BTW: AddComponent-style registration is deprecated, use Register() instead.
Related
Please correct me on the following scenario. ( Question is at the end)
(I asked a similar question that was un-organized and it was voted to close. So I have summarized the question here into a scope that can be replied with exact answers.)
I am developing a web application with multiple layers using nhibernate as ORM. My layer structure is as follow
Model Layer
Repository Layer
Services Layer
UI Layer
with the above layers, the classes and interfaces are placed as below.
ProductController.cs (UI Layer)
public class ProductController : Controller
{
ProductServices _ProductServices;
NHibernate.ISession _Session;
public ProductController()
{
_Session = SessionManager.GetCurrentSession();
_ProductServices = new ProductServices(
new ProductRepository(), _Session);
}
// Cont..
}
ProductServices.cs (Service Layer)
public class ProductServices : IProductServices
{
protected IProductRepository _ProductRepository;
protected NHibernate.ISession _Session;
public ProductServices(IProductRepository productRepository,
NHibernate.ISession session)
{
_ProductRepository = productRepository;
_Session = session;
_ProductRepository.SetSession(_Session);
}
// cont...
}
ProductRepository.cs (Repository Layer)
public class ProductRepository : IProductRepository
{
NHibernate.ISession _Session;
public void SetSession(NHibernate.ISession session)
{
_Session = session;
}
public IEnumerable<Product> FindAll()
{
return _Session.CreateCriteria<Product>().List<Product>();
}
//cont..
}
From the UI layer, I create the session as request per session and inject into service layer with the help of class constructor. Then set the session of repository with a help of a method.
I am afraid if I pass the _Session directly to repository as constructor, I will not have the control over it under the service layer. Also there is a future extension plan for using a webservice layer.
** Is there a way to ensure in each method of ProductRepository class that _Session is set already, without writing the piece of code if(_Session==null) in each and every method as it is repeating the same code.
** If the above pattern is wrong, Please show me a right way to achieve this goal.
What you are doing amazed me a bit. You applying the constructor injection pattern in the ProductService, which is definitely the way to go. On the other hand you are not injecting the dependencies into the ProductController, but that class is requesting one of those dependencies through a static class (this is the Service Locator anti-pattern) and creates a ProductServices class itself. This makes this class hard to test and makes your application less flexible and maintainable, since you can't easily change, decorate or intercept the use of the ProductServices class, when it's been used in multiple places.
And although you are (correctly) using constructor injection for the dependencies in the ProductServices, you are passing those dependencies on to the product repository, instead of applying the constructor injection pattern on the ProductResopistory as well.
Please show me a right way to achieve this goal.
The right way is to apply the constructor injection pattern everywhere. When you do this, your code will start to look like this:
public class ProductController : Controller
{
private ProductServices _ProductServices;
public ProductController(ProductServices services)
{
_ProductServices = services;
}
// Cont..
}
public class ProductServices : IProductServices
{
private IProductRepository _ProductRepository;
public ProductServices(
IProductRepository productRepository)
{
_ProductRepository = productRepository;
}
// cont...
}
public class ProductRepository : IProductRepository
{
private ISession _Session;
public ProductRepository (ISession session)
{
_Session = session;
}
public IEnumerable<Product> FindAll()
{
return _Session
.CreateCriteria<Product>().List<Product>();
}
//cont..
}
See how each class only takes in dependencies that it uses itself. So the ProductController and ProductServices don't depend on ISession (I made the assumption that only ProductRepoistory needs ISession). See how -from a class's perspective- everything is much simpler now?
Did we actually solve a problem here? It seems like we just moved the problem of wiring all classes together up the dependency graph. Yes we did move the problem. And this is a good thing. Now each class can be tested in isolation, is easier to follow, and the application as a whole is more maintainable.
Somewhere in the application however, a ProductController must be created. This could look like this:
new ProductController(
new ProductServices(
new ProductRepository(
SessionManager.GetCurrentSession())));
In its normal configuration, ASP.NET MVC will create controller classes for you, and it needs a default constructor to do so. If you want to wire up controllers using constructor injection (which you should definitely do), you need to do something 'special' to get this to work.
ASP.NET MVC allows you to override the default ControllerFactory class. This allows you to decide how to create controller instances. However, when your application starts to grow, it will get really awkward very quickly when you are creating your dependency graphs by hand (as my last example shows). In this case, it would be much better to use a Dependency Injection framework. Most of them contain a feature / package that allows you to integrate it with ASP.NET MVC and automatically allows to use constructor injection on your MVC controllers.
Are we done yet? Well... are we ever? There's one thing in your design that triggered a flag in my brain. Your system contains a class named ProductServices. Although a wild guess, the name Services seems like you wrapped all product related business operations inside that class. Depending on the size of your system, the number of people on your team, and the amount of changes you need to make, this might get problematic. For instance, how to you effectively apply cross-cutting concerns (such as logging, validation, profiling, transaction management, fault tolerance improvements) in such way that to system stays maintainable?
So instead of wrapping all operations in a single ProductServices class, try giving each business transaction / use case its own class and apply the same (generic) interface to all those classes. This description might be a bit vague, but it is a great way to improve the maintainability of small and big systems. You can read more about that here.
You can use a dependency injection container such as Autofac to instantiate your session and manage the lifetime of it. Leave the responsibility of instantiating the session to Autofac and simply inject the ISession interface into any classes that require the dependency. Have a look at this post: Managing NHibernate ISession with Autofac
You will also find this wiki page useful about configuring Autofac with MVC3: http://code.google.com/p/autofac/wiki/MvcIntegration3
I have some very odd behaviour in my Windsor Container.
I have configured my container like this.
Container = new WindsorContainer();
Container.Kernel.ComponentModelCreated += KernelComponentModelCreated;
Container.Install(FromAssembly.This());
private static void KernelComponentModelCreated(ComponentModel model)
{
if (model.LifestyleType == LifestyleType.Undefined)
model.LifestyleType = LifestyleType.Transient;
}
So I was supposing all my components where I don't specify the lifestyle would get a transient lifestyle and it seemed to don't give any issues until now.
I start multiple asynchronous task which all resolve some components. (So you would expect every task gets a new instance of the component)
However now I know the tasks don't get new instances, because my tasks fail because of crossthreading issues with the component. (so it is being used in multiple tasks)
When I replace the Container.Resolve(somecomponent); With just creating the new component in place everything works like it should.
var contextProvider = MvcApplication.Container.Resolve<IDbContextProvider>();
replaced with
var contextProvider = new DbContextProvider();
So my question is what am I missing here.
The tasks are started in transient configured MVC3 controllers, because of explicitly configured.
The DbContextProvider is resolved in all repositories also configured transient, because of above code.
Another thing I found in the documentation is. You have to release transient components. I implemented all components with IDisposable. But because of auto contructor injection in my controllers I am not completely sure if I have to release them manually and if so how can I do this. (Yes I know I have to call the Release method on the container)
UPDATE
Code below is responsible for releasing and resolving my controllers:
public class WindsorControllerFactory : DefaultControllerFactory
{
private readonly IKernel _kernel;
public WindsorControllerFactory(IKernel kernel)
{
_kernel = kernel;
}
public override void ReleaseController(IController controller)
{
_kernel.ReleaseComponent(controller);
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
if (controllerType == null)
{
throw new HttpException(404, string.Format("The controller for path '{0}' could not be found.", requestContext.HttpContext.Request.Path));
}
return (IController)_kernel.Resolve(controllerType);
}
}
Is there some example available for testing if all dependencies are resolved and released the way they should be? (LifeStyle tests)
I'm not sure if this is what is causing your issues, but you should modify ComponentModel in an implementation of IContributeComponentModelConstruction only.
Check out the documentation of the component model construction contributors for help on how to effectively change the default lifestyle of the container.
Regarding disposal of IDisposables - if you release your controller like you should everything will just work with Windsor :)
I am fairly new to Ninject as well and DI in general. I use NHibernate as my ORM for my MVC app and have been quite happy with my results. That is, until I upgraded from Ninject 2.1 to 2.2.
Now, I get errors within my NinjectWebsiteApplication class due to using Ninject’s Kernel as a resource locator.
Example:
void NinjectWebsiteApplication_BeginRequest(object sender, System.EventArgs e)
{
ILogger logger = Kernel.Get<ILogger>();
logger.Debug(“**********REQUEST BEGIN****************”);
logger.Debug(“**** URL = ” + Request.Url.AbsolutePath);
}
Example 2:
protected override void OnApplicationStarted()
{
var bootstrapper = Kernel.Get<Bootstrapper>();
bootstrapper.RegisterAllAreas();
AreaRegistration.RegisterAllAreas();
......
(More stuff here, like AutoMapper mappings, etc.)
......
}
*The Bootstrapper class is a class I created where I register my routes, global filters, etc.
In both of the above examples, I receive a warning about the Kernel.Get() functions that states the following:
'Ninject.Web.Mvc.NinjectHttpApplication.Kernel' is obsolete: "Do not use Ninject as Service Locator"
After conducting several searches on this, the general consensus is that this is true.
I am trying to work around this, but am at a bit of a loss as to what to do.
I loaded the newest Ninject.Web.Mvc NuGet package which creates the NinjectMVC3 static class under the App_Start folder. I see that they're referencing Microsoft.Web.Infrastructure.DynamicModuleHelper, but I don't see where that fits in to what I'm trying to do.
If anyone has any hints that will help me fix my little mess, I would greatly appreciate it!
The way to deal with the first is not to use the NinjectWebsiteApplication_BeginRequest event but to write a custom global action filter:
public class LogActionFilterAttribute : ActionFilterAttribute
{
private readonly ILogger _logger;
public LogActionFilterAttribute(ILogger logger)
{
_logger = logger;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
_logger.Debug("**********REQUEST BEGIN****************");
_logger.Debug("**** URL = " + filterContext.HttpContext.Request.Url.AbsolutePath);
}
}
and then in your App_Start/NinjectMVC3.cs:
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<ILogger>().To<Logger>();
kernel.BindFilter<LogActionFilterAttribute>(FilterScope.Global, 1);
}
Don't forget to add using Ninject.Web.Mvc.FilterBindingSyntax; in order to bring the BindFilter<> extension method into scope.
And since you have access to the kernel inside the RegisterServices method which happens at application startup you could wire up everything else including your bootstrapper, ...
As far as your Global.asax is concerned you no longer use any Ninject specific stuff in it. You should not derive from NinjectApplication.
The WebActivator infrastructure allows you to have a separate initialization method.
How do I inject dependencies into the global.asax.cs, i.e. the MvcApplication class?
Having previously used the Service Locator (anti-)pattern for dependency injection, I am trying to follow best practice advice in my latest MVC application by using an IOC container (specifically Unity.Mvc3 because it comes with an implementation of the IDependencyResolver out of the box) and constructor injection.
Everything seems quite straight forward so far except for a couple of snags, one of which is in the global.asax.cs (the other is for custom attributes but there's aleady a question on SO covering that).
The HttpApplication event handlers in the MvcApplication class such as:
Application_Start()
Application_EndRequest(object sender, EventArgs e)
Application_AcquireRequestState(object sender, EventArgs e)
may require external dependencies, e.g. a dependency on an ILogService. So how do I inject them without resorting to the service locator (anti-)pattern of e.g.
private static ILogService LogService
{
get
{
return DependencyResolver.Current.GetService<ILogService>();
}
}
Any help/advice greatly appreciated!
The class in your global.asax.cs is your Composition Root, so you can't (and shouldn't) inject anything into it from the outside.
However, there's only one instance of the MvcApplication class, so if you need a service in one of its methods, you can just declare it as a member field - e.g:
public class MvcApplication : System.Web.HttpApplication
{
private readonly ILogService log;
public MvcApplication()
{
this.log = new MyLogService();
}
protected void Application_Start()
{
// ...
this.log.Log("Application started");
}
}
You must use AutofacConfig.Resolve<T>() instead using DependencyResolver.Current.GetService<T>() to get your services without errors.
Using a DI container (in this case, Ninject) is it possible - - or rather, wise to cache a frequently used object for the entire application lifetime (or at least until it is refreshed)?
To cite example, say I have a Template. There are many Template objects, but each user will inherit at least the lowest level one. This is immutable and will never change without updating everything that connects to it (so it will only change on administration demand, never based on user input). It seems foolish to keep querying the database over and over for information I know is not changed.
Would caching this be best done in my IoC container, or should I outsource it to something else?
I already store ISessionFactory (nHibernate) as a Singleton. But that's a little bit different because it doesn't include a query to the database, just the back-end to open and close ISession objects to it.
So basically I would do something like this..
static class Immutable
{
[Inject]
public IRepository<Template> TemplateRepository { get; set; }
public static ITemplate Template { get; set; }
public void Initialize()
{
if(Immutable.Template == null)
{
Immutable.Template = TemplateRepository.Retrieve(1); // obviously better logic here.
}
}
class TemplateModule : Module
{
public void Load()
{
Bind<ITemplate>().ToMethod(() => Immutable.Initialize())InSingletonScope();
}
}
Is this a poor approach? And if so, can anyone recommend a more intelligent one?
I'd generally avoid using staticness and null-checking from your code - create normal classes without singleton wiring by default and layer that aspect on top via the container. Ditto, remove reliance on property injection - ctor injection is always better unless you have no choice
i.e.:
class TemplateManager
{
readonly IRepository<Template> _templateRepository;
public TemplateManager(IRepository<Template> templateRepository)
{
_templateRepository = templateRepository;
}
public ITemplate LoadRoot()
{
return _templateRepository.Retrieve(1); // obviously better logic here.
}
}
class TemplateModule : Module
{
public void Load()
{
Bind<ITemplate>().ToMethod(() => kernel.Get<TemplateManager>().LoadRoot()).InSingletonScope();
}
}
And then I'd question whether TemplateManager should become a ninject provider or be inlined.
As for the actual question... The big question is, how and when do you want to control clearing the cache to force reloading if you decided that the caching should be at session level, not app level due to authorization influences on the template tree? In general, I'd say that should be the Concern of an actual class rather than bound into your DI wiring or hardwired into whether a class is a static class or is a Singleton (as in the design pattern, not the ninject Scope).
My tendency would be to have a TemplateManager class with no static methods, and make that a singleton class in the container. However, to get the root template, consumers should get the TemplateManager injected (via ctor injection) but then say _templateManager.GetRootTemplate() to get the template.
That way, you can:
not have a reliance on fancy ninject providers and/or tie yourself to your container
have no singleton cruft or static methods
have simple caching logic in the TemplateManager
vary the Scoping of the manager without changing all the client code
have it clear that getting the template may or may not be a simple get operation
i.e, I'd manage it like so:
class TemplateManager
{
readonly IRepository<Template> _templateRepository;
public TemplateManager(IRepository<Template> templateRepository)
{
_templateRepository = templateRepository;
}
ITemplate _cachedRootTemplate;
ITemplate FetchRootTemplate()
{
if(_cachedRootTemplate==null)
_cachedRootTemplate = LoadRootTemplate();
return _cachedRootTemplate;
}
ITemplate LoadRoot()
{
return _templateRepository.Retrieve(1); // obviously better logic here.
}
}
register it like so:
class TemplateModule : Module
{
public void Load()
{
Bind<TemplateManager>().ToSelf().InSingletonScope();
}
}
and then consume it like so:
class TemplateConsumer
{
readonly TemplateManager _templateManager;
public TemplateConsumer(TemplateManager templateManager)
{
_templateManager = templateManager;
}
void DoStuff()
{
var rootTempalte = _templateManager.FetchRootTemplate();
Wild speculation: I'd also consider not having a separate IRepository being resolvable in the container (and
presumably having all sorts of ties into units of work). Instead, I'd have the TemplateRepository be a longer-lived thing not coupled to an ORM layer and Unit Of Work. IOW having a repository and a Manager none of which do anything well defined on their own isnt a good sign - the repository should not just be a Table Data Gateway - it should be able to be the place that an Aggregate Root such as Templates gets cached and collated together. But I'd have to know lots more about your code base before slinging out stuff like that without context!