How to find out which assembly handled the request

风格不统一 提交于 2019-11-28 07:45:15
Dan Abramov

As SLaks pointed out, you can check HttpContext.Current.Application.GetType().Assembly.

However I agree with John in the comments that you have probably made a bad design decision if you need this.

The Problem

Your method is a hypocrite.
It talks different to different callers but doesn't tell it in open.

You see, each method defines a certain contract with arguments and a return type.
For example, int.Parse says that it takes a string and turns it into an int. If we want to change default behavior, we may also give it NumberStyles and/or IFormatProvider.

We the consumers don't know how int.Parse is implemented. Because it is static, we most certainly expect it doesn't have side effects and will always return the same value for the same set of parameters.

Repeat this mantra after me:

Explicit is better than implicit.

You would probably be very angry if you found out int.Parse somehow analyzes your code and changes its behavior depending on where it's called from.

It's the caller's responsibility to define the context, not the callee's.

Try to give simple and concise answers to questions below:

  • What happens if the method is called from assembly C?
  • How would you unit-test it? What if some other developer uses this method in unit tests?
  • What happens if you rename assembly A or B? Merge them? Split them further?
  • Will you remember to change this method if anything above happens?

If answering any of the questions above clearly poses a challenge for you, it is a sign you're Doing It Wrong™.

Instead you should...

Introduce a Parameter

Think about the method contract. What can you do to make it full and descriptive?

Define a generic (as in English) method in a separate assembly that doesn't know anything about the callers and has additional parameters, and define parameter-filling shortcuts for it in concrete assemblies.

It's better that these parameters don't know anything about the assemblies either.

For example, if you needed to resolve URLs inside your method, you could accept string baseUrl or Func<string, string> urlResolver so it's potentially usable from any assembly that cares to specify those.

In the worst case, you could define an enum with possible caller contexts and pass it to the method. This will make your design problem explicit, rather than implicit. Obvious problem is always better than hidden problem, although worse than no problem at all.

Check HttpContext.Current.Application.GetType().Assembly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!