Code generate C# class from existing class

304 views Asked by At

I'd like to find a way of generating a C# class from an existing class. For some of my application service classes I like to create a servicebuildertest class to help with unit testing and want to generate this on the fly....

example: I have a class

public class MyAppService
{
   public MyAppService(IRepository<Person> personRepository, etc....)
   {
   }
}

and I want to create the test builder class

public class MyAppServiceTestBuilder
{
    private IRepository<Person> _personRepository;

    public void WithPersonRepository(Mock<IRepository<Person>> personRepository)
    {
        _personRepository = personRepository.Object;
    }

    public void Build()
    {
        return new MyAppService(
         _personRepository ?? new Mock<IRepository<Person>>().Object);
    }
}

Could do with some tips for which technology to use: I've had the following suggestions: CodeDOM, Roslyn, T4.

With T4 it appears that you need a template for each file, which I don't really want, I guess the benefit would be any change to the applicationservice would automatically update the testbuilder.

I started down the route of CodeDOM, but someone suggested that it is an old technology and that Roslyn does the same and a whole lot more...

Many thanks....

0

There are 0 answers