我有一个要求要使用覆盖GlobalService的特定于租户的实现。
public interface IService{
void Process();
}
[Service("Default")]
public class GlobalService: IService{
public virtual void Process(){...}
}
[Service("Tenant1")]
public class Tenant1Service: GlobalService {
public override void Process(){...}
}
[Service("Tenant2")]
public class Tenant2Service: GlobalService {
public override void Process(){ base.Process() ...}
}
因此,通过GlobalService
,所有GlobalService,Tenant1Service and Tenant2Service
都实现了IService
接口。
我已使用 StructureMap 在不同的个人资料
中注册了这些服务GlobalService -> Default Profile
Tenant1Service -> Tenant1 Profile
Tenant2Service -> Tenant2 Profile
我的应用程序是ASP.Net Core 3.0 WebApi。我可以使用以下方法成功检索正确的服务实现:
var profile = container.GetProfile("Tenant1");
var instance = profile.getInstance<IService>(); // return Tenant1Service
我想做的是以某种方式挂接到每个请求并将“默认容器”更改为“配置容器”(如果需要,基于请求参数),但是我找不到诸如SetDefaultContainer之类的方法来进行设置。 / p>
我已经创建了一个中间件类,所以我可以注入和更改容器,但是它不起作用:
public class StructureMapMiddleware
{
RequestDelegate next;
private readonly ILogger log;
public StructureMapMiddleware(RequestDelegate next,ILoggerFactory loggerFactory)
{
this.next = next;
this.log = loggerFactory.CreateLogger<StructureMapMiddleware>();
}
public async Task Invoke(HttpContext context,IContainer container)
{
container = container.GetProfile(context.Request.Headers["Tenant"]);
await next(context);
}
}
在我的控制器或其他服务中,我只想使用构造函数注入
public class MyController : Controller{
public MyController(IService service){...}
}