How to make a strongly typed namespace reference without selecting an arbitrary type in it

I am working on a project in which I am using Depency Injection. When registering a set of interfaces and classes, I need to specify the namespaces on which these interfaces and classes are located.

I don't like providing string constants, though, mainly because it harms refactorism. I do not like to take one of the interfaces / classes and get this namespace. For instance:

typeof(FoodStore.Fruits.IApple).Namespace

because it looks strange that all these arbitrary type names are delayed (why choose IAppleover IOrange?), only to distract from the actual point in the code. There simply is no reasonable rule to choose.

I came up with the following solution.

Put a namespace binding class in each namespace that I need to specify:

namespace FoodStore.Fruits
{
    /// <summary>
    ///     Serves as a type based reference to the namespace this class
    ///     is located in.
    /// </summary>
    public sealed class _NamespaceAnchor
    {
    }
}

Now I can use:

typeof(FoodStore.Fruits._NamespaceAnchor).Namespace

Whenever I reorganize the namespace, I don’t have to worry about registering the DI.

Although this solution satisfies the requirements of the query, I'm still not happy because now I have such ugly empty classes. I cannot make them internalbecause, obviously, the links are distributed through assemblies.

My question is: does anyone know a more elegant solution?

+3
source share
2 answers

, - CLR, . , Type , , .

, Java . , , .

, CLR . , - , , .

+3

, ( ) . , , . .

, , . :

public class TestInterfaceAttribute : Attribute { }

public interface IMyInjectableService { }

[TestInterface]
public class TestService : IMyInjectableService { }

public class RealService : IMyInjectableService { }

, DI ( ), , .

+1

Source: https://habr.com/ru/post/1752697/


All Articles