問題是我有3層項目:DataAccess
DLL和Presentation
DLL取決於Logic
DLL。在邏輯中,我定義了接口od IRepository, IMyIdentityUser
等。在DataAccess中,我使用Microsoft Identity Framework向MyIdentityUser註冊新用戶,該用戶繼承IdentityUser<Guid>
和IMyIdentityUser
接口。我也在使用IoC容器。 假設我在演示文稿(MVC)圖層方法名爲'Register
',參數'RegisterViewModel viewModel
'正在將註冊邏輯委託給Logic
dll中的某個類。創建易失性接口實例 - 依賴注入vs服務定位器
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = MyCore.Resolve<IMyIdentityUser>(); //this is service locator
// antipattern and I want to get
// rid of this
user.UserName = model.Email;
user.Email = model.Email;
var userManager = _userManager;
var result = await userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
var signInManager = _signInManager;
await signInManager.SignInAsync(user, false, false);
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
return View(model);
}
正如您所見我正在使用服務定位器來獲取MyIdentityUser的新實例。我不想將其創建爲'new MyIdentityUser()
',因爲這會迫使我使用與定義了MyIdentityUser的DataAccess dll緊密耦合。 另外,我不想在構造函數參數IMyIdentityUser
中強制每次創建MVC控制器時強制IoC容器創建新的用戶實例。 我想我可以使用某種抽象工廠像
interface IMyIdentityUserFactory
{
IMyIdentityUser CreateNewUser(string name, string email); //any other better arguments?
// not like registerViewModel because
// this view model should be defined in presentation logic
}
,並把它當作參數傳遞給控制器的構造函數(也許在另一個邏輯連接參數門面參數),但我不知道這一點,因爲這是一般與寂寞傳遞IMyIdentityUser
一樣。 有沒有更好的方法來做到這一點?
A.D. 1. 是的,它們不是有狀態的。因此,如果控制器有4個方法,並且只有其中一個需要來自構造函數的新用戶,則每次我們使用剩餘的3個方法時,讓IoC容器創建此用戶會浪費資源 - 假定用戶具有瞬態或每個請求的生命週期。但它不能是單身或者每個線程,並且集中也沒有多大意義。最好爲Register方法創建此用戶**。 當然,新用戶是非常輕的對象,不會影響應用程序的性能,但我仍然想知道如何正確執行此操作。 –
@BartekWójcik我會在更新中回答你! –
@BartekWójcik那麼讓我們在這裏討論這個之前,我的答案添加更新.... –