我正在实施 DI、UnitOfWork 和存储库模式,如下所示:我需要您的专家对此实施的意见,而且我也面临错误。
**Business Domain(Class Lib)**
-Contracts
-IWelcomeService.cs
-Repositories
-BaseRepository.cs
-DataRepository.cs
-IDataRepository.cs
**EF project Lib (I have autogenerated code for Existing Oracle DB)**
-MyEntities.cs (This is additional file I have added for IUnitOfWork implementation
**MVC3 Project (Left default folders for simplicity)**
-Factories
- UnityDependencyResolver.cs
UnityContainerSetup.cs
这些自定义实现的代码如下
我的实体.cs
public partial class MyEntities : ObjectContext, IUnitOfWork
{
#region IUnitOfWork Members
public void Save()
{
base.SaveChanges();
}
#endregion
}
IWelcomeService.cs
public interface IWelcomeService
{
string GetMessage();
}
BaseRepository.cs
public class BaseRepository
{
protected IUnitOfWork UnitOfWork { get; set; }
public BaseRepository(IUnitOfWork unitOfWork)
{
this.UnitOfWork = unitOfWork;
}
}
public interface IUnitOfWork
{
void Save();
}
数据存储库.cs
public class DataRepository : BaseRepository, IDataRepository
{
public DataRepository(IUnitOfWork unitOfWork)
: base(unitOfWork)
{
}
#region IDataRepository Members
public string ChangeMessage()
{
return "Changed by repository";
}
#endregion
}
IDataRepository.cs
public interface IDataRepository
{
string ChangeMessage();
}
UnityDependencyResolver.cs
public class UnityDependencyResolver : IDependencyResolver
{
IUnityContainer _container;
public UnityDependencyResolver(IUnityContainer container)
{
_container = container;
}
#region IDependencyResolver Members
public object GetService(Type serviceType)
{
object instance;
try
{
instance = _container.Resolve(serviceType);
if (serviceType.IsAbstract || serviceType.IsInterface)
return null;
return instance;
}
catch (Exception)
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _container.ResolveAll(serviceType);
}
#endregion
}
UnityContainerSetup.cs
public static void Setup()
{
var container = new UnityContainer();
container.RegisterType<IWelcomeService, WelcomeServices>();
container.RegisterType<IDataRepository, DataRepository>();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
HomeController.cs 公共类 HomeController : Controller { private IWelcomeService _service;
public HomeController(IWelcomeService service)
{
_service = service;
}
public ActionResult Index()
{
ViewBag.Message = _service.GetMessage();
return View();
}
public ActionResult About()
{
return View();
}
}
问题:当我运行应用程序时,出现以下错误:“没有为此对象定义无参数构造函数”
问题:UnitOfWork 何时启动?如何在设置统一容器时注入 IUnitOfWork?