我一直在 MVC 3 应用程序中使用 Ninject,但我正在尝试更改我的数据对象的模式以使用 UnitOfWork,但我无法弄清楚如何让 Ninject 正确处理这个问题。
我知道我的类的实现在我的控制台应用程序中像这样手动构建时起作用:
IDatabaseFactory factory = new DatabaseFactory();
IUnitOfWork worker = new UnitOfWork(factory);
IBlogCategoryDao dao = new BlogCategoryDao(factory);
IBlogCategoryService service = new BlogCategoryService(dao);
BlogCategory category = service.GetById(id);
try
{
if (category != null)
{
service.Delete(category);
worker.Commit();
Console.WriteLine("Category deleted successfully!");
}
else
{
Console.WriteLine("Entity doesn't exist.");
}
}
catch (Exception ex)
{
Console.WriteLine("Error deleting category: {0}", ex.Message);
}
在我的 MVC 3 应用程序中,我使用的是 Ninject.MVC3 NuGet 包,它位于 RegisterServices 方法中。
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IDatabaseFactory>().To<DatabaseFactory>();
kernel.Bind<IUnitOfWork>().To<UnitOfWork>().InRequestScope();
kernel.Bind<IBlogCategoryDao>().To<BlogCategoryDao>();
kernel.Bind<IBlogDao>().To<BlogDao>();
kernel.Bind<IBlogCategoryService>().To<BlogCategoryService>();
kernel.Bind<IBlogService>().To<BlogService>();
}
虽然这在大多数情况下都有效,但不会执行所有 POST 请求(插入、更新、删除)。没有抛出异常,当我单步执行它时,它会毫无问题地通过 SaveChanges() 方法并返回堆栈,但没有执行任何操作。所以我知道我的 Ninject 配置一定遗漏了一些东西。
这是我的工作单元课。
public class UnitOfWork : IUnitOfWork
{
private Database _database; <-- DbContext derived class
private readonly IDatabaseFactory _databaseFactory;
public UnitOfWork(IDatabaseFactory databaseFactory)
{
this._databaseFactory = databaseFactory;
}
public Database Database
{
get
{
return _database ?? (_database = _databaseFactory.Get());
}
}
public void Commit()
{
Database.Commit();
}
}
这是 DatabaseFactory 类:
public class DatabaseFactory : Disposable, IDatabaseFactory
{
private Database _database;
public DatabaseFactory()
{
}
public virtual Database Get()
{
if (_database == null)
{
_database = DataObjectFactory.CreateContext();
}
return _database;
}
protected override void DisposeCore()
{
if (_database != null)
{
_database.Dispose();
}
}
}
还有我的 DataObjectFactory 类:
public static class DataObjectFactory
{
private static readonly string _connectionString;
/// <summary>
/// Static constructor. Reads the connectionstring from web.config just once.
/// </summary>
static DataObjectFactory()
{
string connectionStringName = ConfigurationManager.AppSettings.Get("ConnectionStringName");
_connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
}
/// <summary>
/// Creates the Context using the current connectionstring.
/// </summary>
/// <remarks>
/// Gof pattern: Factory method.
/// </remarks>
/// <returns>Action Entities context.</returns>
public static Database CreateContext()
{
return new Database(_connectionString);
}
}
这与 EFMVC CodePlex 应用程序中使用的模式相似,但我不使用 AutoFac。
对此的任何想法表示赞赏。
谢谢。