Dependency Injection and Code Obfuscation

2019-07-21 06:57发布

问题:

In Mark Seemann's book Dependency Injection in .NET, he states that more people are using DI containers with AUTO-REGISTRATION support where the container can resolve instances of the required concrete types without almost any sort of prior configuration, and this goes well with the convention over configuration architecture approach. but this made me wonder if i used an obfuscator wouldn't this break the code base and cause the container to fail because the conventions have changed ?

回答1:

You can typically still use dependency injection, even if you ship your application assemblies in an obfuscated way. This will work, because you would typically use generic typing (such as Register<IService, Impl>()) or typeof arguments (such as Register(typeof(IService), typeof(Impl))) to register types. In other words, everything the compiler can check for you will still work (when the obfuscator works correctly).

What you should watch closely is everything the compiler can't check. Things as:

  • Override constructor arguments by specifying the name of the argument using a string literal.
  • Any convension over configuration approach where the convension is based on a name instead of type information, such as postfixing the name of constructor arguments with "AppSetting" or "ConnectionString", expecting the name of all types to register end with "Controller", expecting types to be in a particular namespace.

So you will have to watch these issues carefully. Don't forget to safeguard yourself by creating a verifiable configuration and in your case I would verify this configuration on application startup (or add a command line switch so that the application can do a self-check).



回答2:

It all depends on how your DI works. If you do DI based on class or interface name (base classes and marker interfaces for example) and those classes or interfaces sit in an obfuscated library, then yes, your DI will break. If you have a separate library, perhaps a common or core of some sort, which is not obfuscated and its classes and interfaces are used in ID then you'd be OK even if the consuming libraries are obfuscated. Names of external, unobfuscated libraries will not change.

To see an example, take a look with a decompiler at an obfuscated library or exe. You will see that references to external libs, such .NET, are not and cannot be obfuscated.