-2
我試圖在ASP.NET核心(MVC6)應用程序中爲DbContext(EF6)聲明泛型類(Factory)。問題是我需要一個接口類型的依賴注入。C#泛型類與'匹配'通用接口的定義
我已經嘗試了多種方法,而谷歌(一反常態)似乎沒有任何幫助。這或者意味着我的搜索使用了錯誤的詞語,或者我想要做的是完全錯誤的。
所以,問題是:
如果我有一個項目中的兩個DbContexts,我想創建一個通用的工廠,可以創建一個上下文任一使用單一的方法(叫的createContext()),有一個通用的接口,所以我可以使用依賴注入,請問什麼是正確的類定義?
示例接口:
public interface IDbContext<C> where C: DbContext
{
C CreateContext(); //<-- generic bit required here for this method
}
實例廠:
public class DbContextFactory<C> : IDbContext<C>, where C: DbContext //<--unable to get this correct
{
private C _context = null;
private string _connectionstring;
public DbContextFactory(string connectionString)
{
_connectionString = connectionString;
}
public C CreateContext()
{
try
{
var optionsBuilder = new DbContextOptionsBuilder<C>();
optionsBuilder.UseSqlServer(_connectionString);
//_context = new C(optionsBuilder.Options); //<-- issue here also
_context = default(C); //<-- how to pass options??
}
catch (Exception ex)
{
// log some error here
}
return _context;
}
}
關於這個問題的任何幫助將是非常讚賞。 :)
刪除類聲明的逗號:'公共類DbContextFactory:IDbContext 其中C:DbContext' –
DavidG
愚蠢,因爲它似乎,這實際上是回答(用額外的小改動),所以,謝謝你的回答。您是否喜歡這些觀點,因爲如果您「回答」此問題,我很高興獲得獎勵? – MysticSmeg
現在這真的是一個「錯字」的問題,所以我已經投票決定關閉它。 – DavidG