forked from JocaPC/sql-server-rest-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStartUp.cs
87 lines (77 loc) · 3.49 KB
/
StartUp.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// Copyright (c) Jovan Popovic. All Rights Reserved.
// Licensed under the BSD License. See LICENSE.txt in the project root for license information.
using Belgrade.SqlClient;
using Belgrade.SqlClient.SqlDb;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Data.SqlClient;
namespace SqlServerRestApi
{
public static class StartUp
{
public static IServiceCollection AddSqlClient(this IServiceCollection services, string ConnString, Action<Option> init = null)
{
if (init == null)
{
// Adding data access services/components.
services.AddScoped<IQueryPipe>(
sp => new QueryPipe(new SqlConnection(ConnString)));
services.AddScoped<ICommand>(
sp => new Command(new SqlConnection(ConnString)));
return services;
} else
{
return AddSqlClient(services, option => { init(option); option.ConnString = ConnString; });
}
}
public static IServiceCollection AddSqlClient(this IServiceCollection services, Action<Option> init)
{
Option options = new Option();
init(options);
// Adding data access services/components.
string QueryConnString = options.ConnString;
if(options.ReadScaleOut){
if(options.ReadOnlyConnString == null){
QueryConnString = options.ConnString + "ApplicationIntent=ReadOnly;";
} else {
QueryConnString = options.ReadOnlyConnString;
}
}
string ConnString = options.ConnString;
switch (options.ServiceScope) {
case Option.ServiceScopeEnum.SCOPED:
services.AddScoped<IQueryPipe>(
sp => new QueryPipe(new SqlConnection(QueryConnString)));
services.AddScoped<IQueryMapper>(
sp => new QueryMapper(new SqlConnection(QueryConnString)));
services.AddScoped<ICommand>(
sp => new Command(new SqlConnection(ConnString)));
break;
case Option.ServiceScopeEnum.TRANSIENT:
services.AddTransient<IQueryPipe>(
sp => new QueryPipe(new SqlConnection(QueryConnString)));
services.AddTransient<IQueryMapper>(
sp => new QueryMapper(new SqlConnection(QueryConnString)));
services.AddTransient<ICommand>(
sp => new Command(new SqlConnection(ConnString)));
break;
case Option.ServiceScopeEnum.SINGLETON:
services.AddSingleton<IQueryPipe>(
sp => new QueryPipe(new SqlConnection(QueryConnString)));
services.AddSingleton<IQueryMapper>(
sp => new QueryMapper(new SqlConnection(QueryConnString)));
services.AddSingleton<ICommand>(
sp => new Command(new SqlConnection(ConnString)));
break;
}
return services;
}
}
public class Option {
public string ConnString;
public bool ReadScaleOut = false;
public string ReadOnlyConnString;
public enum ServiceScopeEnum { SINGLETON, SCOPED, TRANSIENT };
public ServiceScopeEnum ServiceScope = ServiceScopeEnum.SCOPED;
}
}