我有一个实现洋葱架构的新应用程序现在我想在owin的启动类中注入一个服务。在点击启动类之前启动ioc进程,因为它位于首先使用webactivator运行的引导程序项目中。是否可以在启动类中注入服务?
public class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
// Web API routes
config.MapHttpAttributeRoutes();
ConfigureOAuth(app);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
}
public void ConfigureOAuth(IAppBuilder app)
{
// i want to use an injected service inside a provider :my problem :(
var providers = Providers(service);
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
//For Dev enviroment only (on production should be AllowInsecureHttp = false)
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/generateToken"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
Provider = providers,
AccessTokenFormat = new CustomJwtFormat("http://localhost:18292/")
};
// OAuth 2.0 Bearer Access Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
}
}
答案 0 :(得分:2)
您不必使用StartUp
约定,在这种情况下,最好完全控制应用程序构建管道。这不能直接回答你的问题,更多的是对你如何做到这一点的扩展评论;具体来说,手动设置AppBuilder
并将应用程序发送到Owin服务器。
顺便说一句,我在这里使用nowin来制作实际的服务器。我相信其他人会用Asp.Net的方式回答这个问题。
using AppFunc = Func<IDictionary<string, object>, Task>;
public class App
{
private IAppBuilder _appBuilder;
private HttpConfiguration _config;
private ISomeServiceProvider _provider;
public App(IAppBuilder appBuilder, ISomeServiceProvider provider, HttpConfiguration config)
{
_appBuilder = appBuilder;
_provider = provider;
_config = config;
ConfigureOAuth(_appBuilder, provider);
_appBuilder.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
_appBuilder.UseWebApi(config);
//Build Owin App
_owinApp = (AppFunc) _appBuilder.Build(typeof (AppFunc));
}
void ConfigureOAuth(IAppBuilder app)
{
//...
}
public void Start()
{
//Make an endpoint
var owinEndpoint = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 8080);
//Build WebServer (Nowin)
var owinServer = ServerBuilder.New()
.SetOwinApp(_owinApp)
.SetEndPoint(owinEndpoint)
.Build();
// Start WebServer
using (owinServer)
{
owinServer.Start();
Console.WriteLine("Press ENTER to stop");
Console.ReadLine();
}
}
}
现在在bootstrapper / start up阶段的某处将应用程序添加到容器中,解析并运行它。
public class Program
{
public static void Main(string[] args)
{
var container = GetIoC();
container.Bind<App>().ToSelf();
container.Bind<IAppBuilder>().To(()=>new AppBuilder());
container.Bind<HttpConfiguration>();
// ... other bindings you need
//resolve root
var app = container.Get<App>();
app.Start();
}
}
请记住这是伪代码,但你会得到一般的想法。