注册服务
定义
定义
一、直接注册
1.1 注册实例服务
当服务仅是一个实例类,则可以在AddRpcStore
时,可通过RpcStore
实例,直接注册服务。
public partial class MyRpcServer : SingletonRpcServer
{
/// <summary>
/// 将两个数相加
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
[DmtpRpc(MethodInvoke = true)]//使用函数名直接调用
[Description("将两个数相加")]//其作用是生成代理时,作为注释。
public int Add(int a, int b)
{
var sum = a + b;
return sum;
}
}
.ConfigureContainer(a =>
{
a.AddRpcStore(store =>
{
store.RegisterServer<MyRpcServer>();
//或者按照类型注册
//store.RegisterServer(typeof(MyRpcServer));
});
})
1.2 注册接口服务
当服务是一个接口时,则可以在AddRpcStore
时,通过RpcStore
实例,按注册接口与实例服务。
public interface IMyRpcServer2 : ISingletonRpcServer
{
[DmtpRpc(MethodInvoke = true)]//使用函数名直接调用
int Add(int a, int b);
}
public partial class MyRpcServer2 : SingletonRpcServer, IMyRpcServer2
{
public int Add(int a, int b)
{
var sum = a + b;
return sum;
}
}
.ConfigureContainer(a =>
{
a.AddRpcStore(store =>
{
store.RegisterServer<IMyRpcServer2, MyRpcServer2>();
});
})
提示
使用接口注册服务时,标识Rpc
(例如:DmtpRpc
)特性必须放在接口方法中。否则不会生效。
1.3 注册其他生命周期服务
默认情况下,Rpc
服务是单例注册,即多个请求调用同一个Rpc
服务实例。当服务实例继承TransientRpcServer
(或实现ITransientRpcServer
接口),或者继承ScopedRpcServer
(或实现IScopedRpcServer
接口)时,则服务将会以瞬态,或者区域(此时IOC
容器必须使用IServiceCollection
)被创建。
- 注册为瞬态的服务,在每次调用时,都会创建一个新的服务实例。瞬态服务可以直接通过
this.CallContext
获取调用上下文。 - 注册为区域的服务,在每次调用时,也会创建一个新的服务实例,并且在区域可用时单例。区域服务也可以直接通过
this.CallContext
获取调用上下文。
【瞬态服务】
- 常规
- 泛型
public partial class MyRpcServer : TransientRpcServer
{
[DmtpRpc(MethodInvoke = true)]//使用函数名直接调用
[Description("将两个数相加")]//其作用是生成代理时,作为注释。
public int Add(int a, int b)
{
var callContext= this.CallContext;
var sum = a + b;
return sum;
}
}
public partial class MyRpcServer : TransientRpcServer<IDmtpRpcCallContext>
{
[DmtpRpc(MethodInvoke = true)]//使用函数名直接调用
[Description("将两个数相加")]//其作用是生成代理时,作为注释。
public int Add(int a, int b)
{
var callContext= this.CallContext;
var sum = a + b;
return sum;
}
}
【区域服务】
- 常规
- 泛型
public partial class MyRpcServer : ScopedRpcServer
{
[DmtpRpc(MethodInvoke = true)]//使用函数名直接调用
[Description("将两个数相加")]//其作用是生成代理时,作为注释。
public int Add(int a, int b)
{
var callContext= this.CallContext;
var sum = a + b;
return sum;
}
}
public partial class MyRpcServer : ScopedRpcServer<IDmtpRpcCallContext>
{
[DmtpRpc(MethodInvoke = true)]//使用函数名直接调用
[Description("将两个数相加")]//其作用是生成代理时,作为注释。
public int Add(int a, int b)
{
var callContext= this.CallContext;
var sum = a + b;
return sum;
}
}