Create class that implements a particular design pattern with ReSharper - visual-studio-2010

Design patters are a point of arguments between developers, but I use them very often. Even more, I use one of the most controversial of all common patterns - singleton.
Here is how I implement it in C#:
class MySingletonClass
{
private static volatile MySingletonClass _instance;
private static object syncRoot = new Object();
public static MySingletonClass Instance
{
get
{
if (_instance == null)
{
lock (syncRoot)
{
if (_instance == null)
_instance = new MySingletonClass();
}
}
return _instance;
}
}
private MySingletonClass()
{
}
}
I want to be able to automatically create singleton classes while developing, with only entering a name for the class.
How can I implement this functionality with ReSharper? Can ReSharper pattern catalog be used for this?
Thank you.

You can create a Code Template for it (a File Template if you wish every singleton in a new file).
There are instructions on how to create a template from scratch and from existing code in the help files.

Related

Are there any problems with using a static property to return DbContext

I've been trying to implement a new MVC3 project with Entity Framework 4.1, which instantiates the dbContext on Application_BeginRequest, and disposes it on Application_EndRequest
protected virtual void Application_BeginRequest()
{
HttpContext.Current.Items["_EntityContext"] = new EntityContext();
}
protected virtual void Application_EndRequest()
{
var entityContext = HttpContext.Current.Items["_EntityContext"] as EntityContext;
if (entityContext != null)
entityContext.Dispose();
}
The EntityContext class is defined as follows:
public class EntityContext : MyEntities, IDisposable
{
**//should this be static?**
public static EntityContext Current
{
get { return HttpContext.Current.Items["_EntityContext"] as EntityContext; }
}
void IDisposable.Dispose()
{
Current.Dispose();
}
My question is, will defining my Current property as static cause any problems in a multi-user scenario?
Your lifespan on DbContext is WAY too long. You should be spinning up a bare minimum of one per request, and even better one per access to the database.
As insta pointed out, you should instance the context when you actually need it. There's no advantage making your context lifespan that long.
As a side-note, there's no need to call explicitly the Dispose method, since the .NET Garbage Collector will do that more efficiently for you.
You could instance the context per class, since you're using MVC, instance the context once per Controller.
public class MyTableObjectController : Controller
{
MyContext context = new MyContext();
public ActionResult Index()
{
var model = context.MyTableObjects;
return View(model);
}
}
I might ask, why are you trying to keep your context available between Begin and End request? Are you trying to avoid instancing it?

RavenDB with Ninject in ASP.NET MVC3

I want to use RavenDB with ninject in my asp.net mvc3 project, Any idea how I have to configure this?
kernel.Bind<Raven.Client.IDocumentSession>()
.To<Raven.Client.Document.DocumentStore>()
.InSingletonScope()
.WithConstructorArgument("ConnectionString", ConfigurationManager.ConnectionStrings["RavenDB"].ConnectionString);
Here's how I do mine:
If you install Ninject with Nuget, you'll get an /App_start/ NinjectMVC3.cs file. In there:
private static void RegisterServices(IKernel kernel)
{
kernel.Load<RavenModule>();
}
Here's the RavenModule class:
public class RavenModule : NinjectModule
{
public override void Load()
{
Bind<IDocumentStore>()
.ToMethod(InitDocStore)
.InSingletonScope();
Bind<IDocumentSession>()
.ToMethod(c => c.Kernel.Get<IDocumentStore>().OpenSession())
.InRequestScope();
}
private IDocumentStore InitDocStore(IContext context)
{
DocumentStore ds = new DocumentStore { ConnectionStringName = "Raven" };
RavenProfiler.InitializeFor(ds);
// also good to setup the glimpse plugin here
ds.Initialize();
RavenIndexes.CreateIndexes(ds);
return ds;
}
}
And for completeness here's my index creation class:
public static class RavenIndexes
{
public static void CreateIndexes(IDocumentStore docStore)
{
IndexCreation.CreateIndexes(typeof(RavenIndexes).Assembly, docStore);
}
public class SearchIndex : AbstractMultiMapIndexCreationTask<SearchIndex.Result>
{
// implementation omitted
}
}
I hope this helps!
I recommend using a custom Ninject Provider to set up your RavenDB DocumentStore. First place this in your code block that registers your Ninject services.
kernel.Bind<IDocumentStore>().ToProvider<RavenDocumentStoreProvider>().InSingletonScope();
Next, add this class that implements the Ninject Provider.
public class RavenDocumentStoreProvider : Provider<IDocumentStore>
{
var store = new DocumentStore { ConnectionName = "RavenDB" };
store.Conventions.IdentityPartsSeparator = "-"; // Nice for using IDs in routing
store.Initialize();
return store;
}
The IDocumentStore needs to be a singleton, but do not make the IDocumentSession a singleton. I recommend that you simply create a new IDocumentSession using OpenSession() on the IDocumentStore instance Ninject gives you whenever you need to interact with RavenDB. IDocumentSession objects are very lightweight, follow the unit-of-work pattern, are not thread-safe, and are meant to be used and quickly disposed where needed.
As others have done, you might also consider implementing a base MVC controller that overrides the OnActionExecuting and OnActionExecuted methods to open a session and save changes, respectively.

Need help converting PRISM Unity Module Init to PRISM MEF Module Init

I need help converting the following class for use in a program that I am developing. The original was a demo program from IdeaBlade called "PRISM EXPLORER" based on Unity. I need help converting one part from UNITY to MEF. I handled everything else. Just stuck on this one. I already marked my classes with the MEF "[EXPORT(typeof(XXX))]" and I think I need to use the "ComposeExportedValue" somehow. The confusing part is finding the equivelant for this line:
var provider =
(IEntityManagerProvider) _container.Resolve<IPersistenceGateway>();
_container.RegisterInstance<IEntityManagerProvider>(provider);
THANKS!
The following is the entire class I need to convert. You can find the original here: Ideablade PRISM Page
using Microsoft.Practices.Composite.Modularity;
using Microsoft.Practices.Composite.Regions;
using Microsoft.Practices.Unity;
using PrismExplorer.Infrastructure;
namespace ModelExplorer.Explorer {
public class ExplorerModule : IModule {
private readonly IUnityContainer _container;
public ExplorerModule(IUnityContainer container) {
_container = container;
}
public void Initialize() {
InitializeContainer();
SetViews();
}
// ToDo: Consider getting from configuration
private void InitializeContainer() {
RegisterGatewayAndEntityManagerProvider();
_container.RegisterType<IQueryRepository, QueryRepository>(
new ContainerControlledLifetimeManager()); // singleton
}
private void RegisterGatewayAndEntityManagerProvider() {
_container.RegisterType<IPersistenceGateway, PrismExplorerPersistenceGateway>(
new ContainerControlledLifetimeManager()); // singleton
var provider =
(IEntityManagerProvider) _container.Resolve<IPersistenceGateway>();
_container.RegisterInstance<IEntityManagerProvider>(provider);
}
private void SetViews() {
var regionManager = _container.Resolve<IRegionManager>();
var view = _container.Resolve<ExplorerView>();
regionManager.AddToRegion(RegionNames.MainRegion, view);
regionManager.RegisterViewWithRegion(RegionNames.MainRegion, typeof(ExplorerView));
}
// Destructor strictly to demonstrate when module is GC'd
//~MevModule() {
// System.Console.WriteLine("Goodbye, MevModule");
//}
}
}
The two corresponding methods on a CompositionContainer are ComposeExportedValue<T>(...), which allows you to add a specific instance to the container, and GetExportedValue<T>(...) which gets an instance of T from the container.
If you can design your types in a way to reduce this use of service location and try and prefer constructor injection, it will make your code much easier to maintain and test. E.g., could your code be transformed into:
[Export(typeof(IModule))]
public class ExplorerModule : IModule
{
[ImportingConstructor]
public ExplorerModule(IPersistenceGateway gateway)
{
}
}

How to generate code based on another class?

To create our test data, we use the following variation of the Builder pattern (simplified example!):
Sample class:
public class Person
{
public string Name { get; set; }
public string Country { get; set; }
}
The builder:
public class PersonBuilder
{
private string name;
private string country;
public PersonBuilder()
{
SetDefaultValues();
}
private void SetDefaultValues()
{
name = "TODO";
country = "TODO";
}
public Person Build()
{
return new Person
{
Name = name,
Country = country
};
}
public PersonBuilder WithName(string name)
{
this.name = name;
return this;
}
public PersonBuilder WithCountry(string country)
{
this.country = country;
return this;
}
}
NOTE: The context of the example itself is not relevant. The important thing here is how in the example, the a builder class like PersonBuilder can completely be generated by looking at the entity class (Person) and applying the same pattern - see below.
Now imagine that the person class has 15 properties instead of 2. It would take some monkeywork to implement the builder class, while theoretically, it could automatically be generated from the Person class. We could use code generation to quickly set up the builder class, and add custom code later if needed.
The code generation process would have to be aware of the context (name and properties of the person class), so simple text-based code generation or regex magic doesn't feel right here. A solution that is dynamic, not text-based and can be triggered quickly from inside visual studio is preferred.
I'm looking for the best way to perform code generation for scenarios like this.
Reflection? Codesmith? T4 templates? Resharper Live templates with macros?
I'm looking forward to see some great answers :)
The T4 solution is a well Visual Studio integrated option. You can use reflection inside the T4 template to actually generate the code.
We added a feature in CodeSmith Generator 5.x that allows you to generate off of existing code. Please take a look at that documentation here. Also you can use reflection or any .NET library in a CodeSmith Generator Template.
Thanks
-Blake Niemyjski
If it is for test only, consider a mocking framework like RhinoMocks:
internal class PersonBuilder
{
private MockRepository _mockRepository;
private IPerson _person;
public PersonBuilder()
{
_mockRepository = new MockRepository();
_person = _mockRepository.Stub<IPerson>();
}
public PersonBuilder WithName(string name)
{
_person.Name = name;
return this;
}
public PersonBuilder WithCountry(string Country)
{
_person.Country= Country;
return this;
}
public IPerson Build()
{
_mockRepository.ReplayAll();
return _person;
}
}
This way your builder can evolve along with your need. Further, you don't need to change your Build method. Just add "WithX" methods.
Have a look into the ABSE modeling approach and its IDE, AtomWeaver. ABSE is a template-based modeling and code generation framework, where a model (has nothing to do with UML or MDA) is created by applying "building blocks" (Atoms). These Atoms are template/program hybrids and are context-aware: an Atom can generate code according to its placement on the tree and on the presence/absence of certain Atoms.
The model host (AtomWeaver in this case) will "execute" the model in order to obtain the desired source code. The model can be "the source": change the model and regenerate as many times as necessary.
AtomWeaver is not integrated into Visual Studio, but can work alongside it without any problems.

Using 'System.Lazy.LazyThreadSafetyMode' with MEF

I import many parts from different assemblies into my class like this:
[ImportMany(typeof(IServiceProvider))]
private IEnumerable<Lazy<IServiceProvider, IDictionary<string, object>>> ServiceProviders
{
get;
set;
}
After parts imported, Service providers are created on demand:
private IServiceProvider GetServiceProvider(String name)
{
foreach (var serviceProvider in ServiceProviders)
{
String currentName = (String)serviceProvider.Metadata["Name"];
if (currentName == name)
return serviceProvider.Value; // Many threads receive here and try to create new instance.
}
return null;
}
As I commented in above code, many threads try to get value of the lazy variable (create new instance of it, if not created yet) at the same time.
Lazy<T>has a constructor which allow to create instance (value) in a thread-safe manner, like this:
// Something here...
Dictionary<string, object> metadata = new Dictionary<string,object>();
metadata.Add("Name", "test");
Lazy<IServiceProvider, IDictionary<string, object>> serviceProvider = new Lazy<IServiceProvider, IDictionary<string, object>>(ServiceProviderValueFactory, metadata, System.Threading.LazyThreadSafetyMode.ExecutionAndPublication);
// Now access to 'serviceProvider.Value' creates an instance (if not created yet) in a thread-safe manner.
private IServiceProvider ServiceProviderValueFactory()
{
// Create and return a new instance of 'IServiceProvider'.
}
MEF take cares of object creation when importing parts and I want to use the Lazy constructor which allows for thread-safe value creation but I don't know how.
When creating your CompositionContainer, pass isThreadSafe=true to the constructor.
Note that it's not safe to do any recomposition in a thread-safe container, so you shouldn't use catalogs that change, or CompositionBatch, or the AttributedModelServices.ComposeParts() extension method.
I'm not convinced this is something you can change. The Lazy<T, M> type is initialised through the ExportServices internal class, and cannot be overridden. If you subclassed ExportProvider the target GetExports or GetExportsCore that return Lazy<T, M> are not abstract or virtual so cannot be overridden.
In ExportServices, it is hard coded as:
return new Lazy<T, M>(..., LazyThreadSafetyMode.PublicationOnly);

Resources