Reputation: 974
Background I am going to provide the background here before posing my actual question:
I am working on an ASP.NET MVC 4 project in C#. The current development task I am busy with is to implement RazorMachine (https://github.com/jlamfers/RazorMachine) in this web application in order to leverage the use of the Razor engine in my application layer (as opposed to purely in the MVC web layer). I have successfully implemented RazorMachine in a series of Test Fixtures and all is working great. Now, I need to implement it into my application architecture inside my application layer.
In his CodeProject article on RazorMachine (http://www.codeproject.com/Articles/423141/Razor-2-0-template-engine-supporting-layouts), Jaap Lamfers states "Please note that normally for performance reasons at any application you would create a singleton instance of RazorMachine (because of the inner instance bound JIT created type caching)".
A very basic example of the code in action is as follows:
RazorMachine rm = new RazorMachine();
ITemplate template = rm.ExecuteContent("Razor says: Hello @Model.FirstName @Model.LastName",
new {FirstName="John", LastName="Smith"});
Console.WriteLine(template.Result);
You can view more code samples on the CodeProject site.
With this as background, my question is as follows:
What is the best way to provide a single instance of the RazorMachine object to my MVC application?
Let me state that I am aware of the Singleton and Factory patterns and their possible implementations. However, using Singleton doesn't seem to sit right as I am not writing the class from scratch, the class already exists. Factory also seems to not be wholly appropriate, but I would like to hear what others say.
All input will be greatly appreciated.
Upvotes: 0
Views: 697
Reputation: 138
THe quickest, easiest way to get a singleton instance of RazorMachine is to use your DI container of choice, examples of well known DI containers are Autofac, Ninject, Castle Windsor, Unity, StructureMap (see this link for a performance comparision of major .NET Ioc/DI containers: http://www.palmmedia.de/blog/2011/8/30/ioc-container-benchmark-performance-comparison)
These containers abstract away from you the developer the responsibility to correctly implementing the Singleton pattern.
Using Autofac, to register a singleton instance of a class you would do the following:
var builder = new ContainerBuilder();
builder.RegisterType<YourClassGoesHere>().SingleInstance();
Ref:http://autofac.readthedocs.org/en/latest/lifetime/instance-scope.html#single-instance
Upvotes: 1