0%

T1.SourceGenerator nuget

T1.SourceGenerator

We provide following features

  • Simple Auto Mapping Clone Object Function
  • Simple Auto Mapping any interface to WebApi Client Class

How do I get started ?

First, install T1.SourceGenerator nuget package.
Attach AutoMapping Attribute on any class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using T1.SourceGenerator.Attributes;
namespace MyDemoApp;

[AutoMapping(typeof(Employee))]
public class User
{
public string Name { get; set; }
public int Level { get; set; }
public int Vip { get; set; }
}

public class Employee
{
public string Name { get; set; }
public float Level { get; set; }
public int Vip { get; }
}

Then in your application code, execute the mappings:

1
2
var source = new User();
var dto = source.ToEmployee();

If you hope change ToEmployee() method to other extension method, you can do this:

1
2
3
4
5
6
7
[AutoMapping(typeof(Employee), "CloneToEmployee")]
public class User
{
public string Name { get; set; }
public int Level { get; set; }
public int Vip { get; set; }
}

Then in your application code, execute the mappings:

1
2
var source = new User();
var dto = source.CloneToEmployee();

How to get Auto Mapping WebApiClient class ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[WebApiClient(ClientClassName = "SamApiClient", Namespace = "ConsoleDemoApp")]
public interface IMyApiClient
{
[WebApiClientMethod("mgmt/test1", Method = InvokeMethod.Get, Timeout = "00:00:10")]
void Test(Request1 req);

[WebApiClientMethod("mgmt/test2", Timeout = "00:00:30")]
void Test2();

[WebApiClientMethod("mgmt/test3")]
Response1 Test3();

[WebApiClientMethod("mgmt/test4")]
Response1 Test4(int a);
}

Then in your application code, execute the code:

1
2
3
using T1.SourceGenerator;

var client = new SamApiClient(null);

If you prefer a different namespace (“ConsoleDemoApp”), you can custom it.

1
2
3
4
5
[WebApiClient(ClientClassName = "SamApiClient", Namespace = "ConsoleDemoApp")]
public interface IMyApiClient
{
...
}

If you need constructor injection, you can do it like in the following program example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
[WebApiClient(ClientClassName = "SamApiClient", Namespace = "ConsoleDemoApp")]
[WebApiClientConstructorInject(MyConfig), "myConfig")]
public interface IMyApiClient
{
...
}

partial class SamApiClient
{
partial void Initialize()
{
BaseUrl = _myConfig.BaseUrl;
}
}

Even if you need to specify a variable using a special method for constructor injection, you can do it this way.

1
2
3
4
5
6
[WebApiClient(ClientClassName = "SamApiClient", Namespace = "ConsoleDemoApp")]
[WebApiClientConstructorInject(typeof(IOption<MyConfig>), "myConfig", AssignCode="myConfig.Value")]
public interface IMyApiClient
{
...
}

It will produce the following code.

1
2
3
4
5
6
7
8
public class SamApiClient
{
public SamApiClient(IHttpClientFactory httpClientFactory,
IOption<MyConfig> myConfig)
{
_myConfig = myConfig.Value;
}
}