开发者

Inherit from a type by reflection

开发者 https://www.devze.com 2023-03-19 08:55 出处:网络
I\'m developping a log4net wrapper and I must inherit a custom class from log4net.Core.LogImpl to provide a TRACE level.

I'm developping a log4net wrapper and I must inherit a custom class from log4net.Core.LogImpl to provide a TRACE level.

With a reference to log4net, I would have :

using log4net.Core;

public class TraceLogImpl : LogImpl, ITraceLog
{
...
}

The problem is that I m开发者_开发技巧ust have no direct reference to log4net.dll in my projet : the library is in the bin directory (that way, I do not depend on a specific version of log4net) and it is loaded at runtime.

-> I can't use "using log4net.Core".

My question is : how can I inherit from this type by using reflection?

Thank you for your help!


You can't, basically.

It sounds like you should possibly extract this into a separate project which does depend on log4net, and effectively treat it as an extra part of log4net itself (versioned alongside it etc).


You can inherit from a class at a runtime, by creating dynamic assembly and injecting some IL code into it. Here is an example of library, that inherits from an unknown interface and known class at runtime.

So, the recipe is might be like this:

  1. Create an Interface that contains all methods, that you need from log2net and some extra tracing methods.
  2. At runtime create an implementation of this interface, that will route all calls to log2net with required modifications or tracing
  3. Provide factory method to create instances of dynamic class

However, I would'd be glad to debug this later.


To inherit from a class using reflection, your class has to be created via reflection itself. Take a look at Reflection.Emit.

But, to work with dynamic loaded assemblies, the best way is to have a set of well defined interfaces that you can then use to reference dynamic loaded types. You don't extend a class through inheritance, but by composition, using something like the strategy pattern.


I would say that Reflection is a runtime action where as inheritance is an action performed during compilation. You might be able to do something with CodeDom and build a dynamic class at runtime, but I am not sure it will give you what you need.


If you want to add a custom level to log4net, you don't have to write code; Just by using configuration you can add your own levels

0

精彩评论

暂无评论...
验证码 换一张
取 消