Pergunta

i have a file which will be used across many app projects. the only difference of these files is the webservice reference name. code like this:

public void Test(){
    Kevin.ServiceReference1.Service1Client client = new Kevin.ServiceReference1.Service1Client();
    // do something....
}

like code above, the 'Kevin.ServiceReference1' will be replace by specified app project namespace. so, according to DRY(don't repeat yourself), i shouldn't just copy the file to many projects and rename the specified part manually. is there any way i can easily replace some parts of my template file to something related to the project?

Foi útil?

Solução

Have you looked into Microsoft's T4 code templating system ? It might be just what you need.

Links: http://msdn.microsoft.com/en-us/vstudio/cc308634.aspx
http://visualstudiomagazine.com/articles/2009/05/01/visual-studios-t4-code-generation.aspx

Outras dicas

This isn't a question of DRY; while the files might look similar, *you aren't repeating yourself because the one and only operation -- the declaration and assignment of a variable -- is different for every type**.

While you might want to look into giving your classes a common parent if they share a common purpose, there's nothing in your example that suggests that the classes are, in fact, related in any way.

If you're looking for ways to automate the process to make it easier on yourself, check out T4 Templates (free from Microsoft), or PostSharp. There are many other threads on here about code generation.

If the only thing changing in the file is the namespace and class name, you can extract all of the other common functionality into a base class. Then, for each different usage, make a derived class inheriting from the base class. The derived class could just have a simple method that would return the specific namespace/class.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top