How to prevent the use of the .NET base class?

I am working on a project where I need to extend a WebClient for a custom implementation, MyWebClient .

I also need to make sure that MyWebClient is the only version implemented by any project developer, and no one uses the base class WebClient .

Is it possible to prevent the use of WebClient , given that this is not code that I have access to?

+1
source share
4 answers

Depending on the features of WebClient you need to consider implementing MyWebClient as a proxy server that provides only those methods that you allow to use from a member of WebClient .

Example:

 public class MyWebClient { private WebClient HiddenWebClient {get; set;} // proxy sample public void DownloadFile(string address, string fileName) { HiddenWebClient.DownloadFile(address, fileName); } // other proxy methods & your specific implementation come here. } 

After that, you will need a dedicated ctor and possibly a factory to properly create MyWebClient .

This will not prevent your developers from using WebClient , which would be too complicated (see, for example, the @gdoron suggestion), but will help to avoid using it by mistake.

Edit:

From your last comment, I think that all you need is a factory that will install the User Agent for all your WebClient instances.

Then, depending on your organization, you will need a strong usage message (and perhaps a search tool to find new WebClient() in your projects).

 public static class WebClientFactory { public static WebClient Create() { WebClient result = new WebClient(); result.Headers.Add("My Fancy User Agent"); return result; } } 
+2
source

The best way to do this is to check the code for all the code and ensure that WebClient is not in use. Another option is to schedule the night task and pull it out of the source control and search for each file in the project to make sure that they use WebClient instead of MyWebClient (it would be easier to do this with Roslyn). The bottom line is that this is not a problem with the code (or should not be), it should be a problem with learning.

+1
source

If you really need it (which I seriously doubt it) The only way to do this is to reflect.

When the application starts scanning the code of all methods and classes in Assembly and make sure that they do not use the forbidden WebClient class.

I guess you won’t do it ...

0
source

If you use ReSharper, you can use the "Search with Template" function and configure it to automatically convert WebClient code to your MyWebClient , simply by pressing the magic key combination ALT + Enter!

See: http://www.jetbrains.com/resharper/webhelp/Reference__Search_with_Pattern.html

0
source

All Articles