在Configure方法中使用DependencyInjection

时间:2017-08-22 15:39:14

标签: c# asp.net dependency-injection asp.net-core-mvc asp.net-core-1.1

在ASP.NET CORE Web应用程序中,我有一个class BookInfo(convrMgr: ConversationMgr, id: String, queue: RequestQueue, queueTag:String) { val TAG = "BookInfo" var title: String? = "" init { val url = "https://api.douban.com/v2/book/$id" // Request a string response from the provided URL. val stringRequest = StringRequest(Request.Method.GET, url, Response.Listener<String> { response -> Log.d(TAG + " Response", response.substring(0)) // Parse JSON from String value val parser = Parser() val jsonObj: JsonObject = parser.parse(StringBuilder(response.substring(0))) as JsonObject // Initial book title of book properties. title = jsonObj.string("title") Log.d(TAG + " Book title", title) convrMgr.addNewMsg(title) }, Response.ErrorListener { error -> Log.e(TAG + " Error", error.toString()) }) // Set the tag on the request. stringRequest.tag = queueTag // Add the request to the RequestQueue. queue.add(stringRequest) } 类和一个接口MyRepository来管理对存储库(数据库)的访问。

每次用户连接到应用程序(在站点上)时,我都需要在数据库中记录一个条目。

在Startup.cs中,我使用IMyRepository方法

ConfigureServices

然后在public void ConfigureServices(IServiceCollection services) { // Adds services required for using options. services.AddOptions(); // ... services.AddSingleton<IMyRepository, MyRepository>(); 方法中我需要更新数据库

Configure

所以我的问题是如何/在哪里注入public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { // ... IMyRepository myRep = ??? // should inject somehow // ... app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions { ClientId = Configuration["...ClientId"], Authority = Configuration["...AADInstance"] + Configuration["...TenantId"], CallbackPath = Configuration["...CallbackPath"], Events = new OpenIdConnectEvents { OnTicketReceived = context => { var user = (ClaimsIdentity)context.Ticket.Principal.Identity; if (user.IsAuthenticated) { var firstName = user.FindFirst(ClaimTypes.GivenName).Value; var lastName = user.FindFirst(ClaimTypes.Surname).Value; var email = user.FindFirst(ClaimTypes.Email).Value; var connectedOn = DateTime.UtcNow; var userId = user.Name; // // HERE ADD the info in the DB via IMyRepository // myRep.AddUserInfo(userId, firstName, lastName, email, connectedOn); } return Task.FromResult(0); } } }); // ... } 以便在IMyRepository方法中使用它?

1 个答案:

答案 0 :(得分:3)

修改您的Configure方法以获取其他参数IMyRepository myRep,只要您在ConfigureServices注册该参数,就会为其注入。

public void Configure(IApplicationBuilder app, 
                      IHostingEnvironment env, 
                      ILoggerFactory loggerFactory, 
                      IMyRepository myRep) { ... }