Stef Heyenrath 2528cf3f2d PackageTags
2021-07-25 11:38:49 +02:00
2021-07-23 16:02:28 +02:00
2021-07-25 11:36:35 +02:00
2021-07-23 16:02:28 +02:00
2021-07-25 11:35:32 +02:00
2021-07-25 11:36:35 +02:00

ProxyInterfaceSourceGenerator

This project uses Source Generation to generate an interface and a Proxy class for classes. This makes it possible to wrap external classes which do not have an interface, in a Proxy class which makes it easier to Mock and use DI.

Install

NuGet Badge

You can install from NuGet using the following command in the package manager window:

Install-Package ProxyInterfaceGenerator

Or via the Visual Studio NuGet package manager or if you use the dotnet command:

dotnet add package ProxyInterfaceGenerator

Usage

Given: an external existing class which does not implement an interface

public sealed class Person
{
	public string Name { get; set; }
}

Create a partial interface

And annotate this with ProxyInterfaceGenerator.Proxy with the Type which needs to be wrapped:

[ProxyInterfaceGenerator.Proxy(typeof(ProxyInterfaceConsumer.Person))]
public partial interface IPerson
{
}

When the code is compiled, this source generator creates the following

1. An additional partial interface

Which defines the same properties and methods as in the external class.

public partial interface IPerson
{
	string Name { get; set; }
}

2. A Proxy class

Which takes the external class in the constructor and wraps all properties.

public class PersonProxy
{
	public Person _Instance { get; }

    public PersonProxy(Person instance)
    {
        _Instance = instance;
    }

    public string Name { get => _Instance.Name; set => _Instance.Name = value; }
}

Use it

IPerson p = new PersonProxy(new Person());
p.Name = "test";
S
Description
This project uses Source Generation to generate an interface and a Proxy class for classes. This makes it possible to wrap external classes which do not have an interface, in a Proxy class which makes it easier to Mock and use Dependency Injection.
Readme 603 KiB
Languages
C# 99.9%