Search code examples
c#design-patternspostsharp

PostSharp singleton


I wish I have a PostSharp-powered singleton pattern?

Is it possible for PostSharp?

Is there an existing example or project?

Want to so something like:

interface ISingleton
{
    void Refresh();
    object Instance{get;set;}
}

[Singleton(AutoRefresh=true, AutoRefreshInterval=20)]
public class Repository
{
    private Repository()
    {
        //Code to load data...
    }
    public DoSomething()
    {
        //Do something at instance level;
    }
    public void Refresh()
    {
        //Refresh data
    }
}

SingletonAttribute should make the class to implement ISingleton and insert code for Instance Property and Refresh() method body

When using the class:

((Repository as ISingleton).Instance as Repository).DoSomething();

Solution

  • As far as I can understand, you want to control an object's lifetime. That's not what you can do with AOP alone. Things like that are usualy managed by using IoC container (Unity, Windsor, Ninject) and setting up object's lifetime (such options as singletone, one instance per thread, one instance per request are available). If you use an IoC container, you can write your own attribute, so you can take all classes with, for example, [Singletone] attribute and register them with a singletone lifetime within a container. Then when consumers of your class resolve the instance from the container, they will always get the same instance.