Search code examples
c#fluent-interfaceglobal-methods

Fluent Interface, Need something like global methods in C#


Im currently trying to build a Fluent Interface for a ServiceLocator. To ensure that each the developer can easily setup 1-to-n mappings

I'd like something like this

ServiceLocator.Instance.For<IFoo>(Use<Foo>(), Use<FooBar>());

Singleton is workin fine... the methodsignature for the For method looks like this

public void For<TInterface>(params type[] services)
{
// ... 
}

So I was looking for something like a global method

C# has some global methods, all methods which are defined on System.Object. But when I create a new generic ExtensionMethod on System.Object, the method will not be visible.

public static class MyExtensions
{
  public static void Use<T>(this Object instance)
  {
    // ..
  }
}

MethodChaining would be the alternative, but this approach looks sexy :D

Has anyone an idea?


Solution

  • Well, actually when I create an extension method for Object, it is visible. As in,

    public static class Extensions
    {
        public static void doStuff<T>(this T myObject)
        {
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            int a = 5;
            a.doStuff();
    
            string b = "aaa";
            b.doStuff();
    
            List<int> c = new List<int>() { 1, 2, 3, 10 };
            c.doStuff();
    
            Extensions.doStuff(c);        
        }
    }
    

    Did I misunderstand your question?