Ninject 在 Winform、 Asp.net MVC中结合EntityFramework的使用( 注入同一个DbContext的使用方法) - 原创
Ninject 在 Winform、 Asp.net MVC 中结合EntityFramework的使用( 注入同一个DbContext的使用方法)
Demo中用到了 RepositoryT.dll, RepositoryT.EntityFramework.dll,Ninject.dll,Ninject.Web.MVC.dll, Ninject.Web.Common.dll
代码写的比较乱,也没重构 拷贝来拷贝去,作为一个合格的程序员确实有点糟糕,不过还好 能说明事情,大家将就看吧 呵呵 :)
使用到的自定义类:
//业务相关的类
DataAccessRepository.cs
IDataAccessRepository.cs
//Ninject相关的类
DataAccessNinjectModule.cs
DataAccessKernelBase.cs
DataAccessRepositories.cs
//UnitTest 使用
TestNinjectClass.cs
UserTest.cs
//Winform 使用
Program.cs
Form1.cs
//ASP.NET MVC中使用:
AccountController.cs
/App_Start/NinjectWebCommon.cs
具体内容:
//业务相关的类
IDataAccessRepository.cs
using RepositoryT.Infrastructure; using System; using System.Collections.Generic; using System.Data.Entity.Infrastructure; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataAccess { public interface IDataAccessRepository<TEntity> : IRepository<TEntity> where TEntity : class { DbEntityEntry GetDbEntityEntry(TEntity entity); } }
DataAccessRepository.cs
using RepositoryT.EntityFramework; using RepositoryT.Infrastructure; using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace DataAccess { public class DataAccessRepository<T, TContext> : RepositoryBase<TContext>, IDataAccessRepository<T> where T : class where TContext : class, IDbContext, IDisposable { private readonly IDbSet<T> _dbset; public DataAccessRepository(IDataContextFactory<TContext> databaseFactory) : base(databaseFactory) { _dbset = DataContext.Set<T>(); } public virtual void Add(T entity) { _dbset.Add(entity); }
public DbEntityEntry GetDbEntityEntry(T entity)
{
return DataContext.Entry(entity);
} } }
//Ninject相关的类
DataAccessNinjectModule.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Ninject.Modules; using DataEntities; using Ninject.Activation; using Ninject; using RepositoryT.EntityFramework; using RepositoryT.Infrastructure; namespace DataAccess { public class DataAccessNinjectModule : NinjectModule { public override void Load() { var testNinjectEntities = new TestNinjectEntities(); //Kernel.Bind<ILoginRepository>() // .To<LoginRepository>(); var factory = new DefaultDataContextFactory<TestNinjectEntities>(); Kernel.Bind<IDataAccessRepository<Login>>() .To<DataAccessRepository<Login, TestNinjectEntities>>() .InSingletonScope() .WithConstructorArgument("databaseFactory", factory); Kernel.Bind<IUnitOfWork>() .To<UnitOfWork<TestNinjectEntities>>() .InSingletonScope() .WithConstructorArgument("databaseFactory", factory); } } }
DataAccessKernelBase.cs
using Ninject; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataAccess { public class DataAccessKernelBase { public Ninject.IKernel Kernel { get { var kernel = new StandardKernel(new DataAccessNinjectModule()); return kernel; } } } }
DataAccessRepositories.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Ninject; using DataEntities; using DataAccess; using RepositoryT.Infrastructure; namespace DataAccessUnitTestProject { public class DataAccessRepositories : DataAccessKernelBase { public IDataAccessRepository<Login> DataAccessRepository { get { return Kernel.Get<IDataAccessRepository<Login>>(); } } public IUnitOfWork UnitOfWork { get { return Kernel.Get<IUnitOfWork>(); } } public TestNinjectClass TestNinjectClass //这个属性相当重要。用这个属性Ninject可以自动注入Kernel里有的类型参数 { get { return Kernel.Get<TestNinjectClass>(); } } } }
//UnitTest 使用
TestNinjectClass.cs
using DataAccessUnitTestProject; using DataEntities; using RepositoryT.Infrastructure; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataAccess { public class TestNinjectClass { IDataAccessRepository<Login> DataAccessRepository; IUnitOfWork UnitOfWork; public TestNinjectClass(IDataAccessRepository<Login> dataAccessRepository, IUnitOfWork unitOfWork) { DataAccessRepository = dataAccessRepository; UnitOfWork = unitOfWork; } public void TestSave() { DataAccessRepository.Add(new Login() { UserName = "admin123aa", Password = "123aa" }); UnitOfWork.Commit(); } } }
UserTest.cs
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Ninject; using DataAccess; using DataEntities; using RepositoryT.EntityFramework; using RepositoryT; using RepositoryT.Infrastructure; using System.Threading.Tasks; namespace DataAccessUnitTestProject { [TestClass] public class UserTest { [TestMethod] public void TestSave() { DataAccessRepositories rs = new DataAccessRepositories(); rs.TestNinjectClass.TestSave(); } } }
//Winform 使用
Program.cs
namespace WindowsFormsApplication { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var kernel = new StandardKernel(new DataAccessNinjectModule()); var form = kernel.Get<Form1>(); Application.Run(form); } } }
Form1 .cs
using DataAccess; using DataEntities; using RepositoryT.Infrastructure; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication { public partial class Form1 : Form { public Form1() { InitializeComponent(); } IDataAccessRepository<Login> _DataAccessRepository; IUnitOfWork _UnitOfWork; public Form1(IDataAccessRepository<Login> dataAccessRepository, IUnitOfWork unitOfWork) { _DataAccessRepository = dataAccessRepository; _UnitOfWork = unitOfWork; if (_DataAccessRepository != null && _UnitOfWork != null) { var b = true; try { _DataAccessRepository.Add(new DataEntities.Login() { UserName = "Admin", Password = "123", }); _UnitOfWork.Commit(); } catch (Exception) { b = false; } } } } }
//ASP.NET MVC中使用:
AccountController.cs
[Authorize] public class AccountController : Controller { IDataAccessRepository<Login> _LoginDataAccessRepository; IUnitOfWork _UnitOfWork; public AccountController(IDataAccessRepository<Login> loginDataAccessRepository, IUnitOfWork unitOfWork) { _LoginDataAccessRepository = loginDataAccessRepository; _UnitOfWork = unitOfWork; }
public ActionResult Save(LoginModel model, string returnUrl)
{
var b = true;
try
{
_LoginDataAccessRepository.Add(new DataEntities.Login()
{
UserName = model.UserName,
Password = model.Password,
});
_UnitOfWork.Commit();
}
catch (Exception)
{
b = false;
}
if (b)
{
return RedirectToLocal("http://www.ideaam.com");
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
}
/App_Start/NinjectWebCommon.cs
[assembly: WebActivator.PreApplicationStartMethod(typeof(MvcApplication.App_Start.NinjectWebCommon), "Start")] [assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(MvcApplication.App_Start.NinjectWebCommon), "Stop")] namespace MvcApplication.App_Start { using System; using System.Web; using Microsoft.Web.Infrastructure.DynamicModuleHelper; using Ninject; using Ninject.Web.Common; using Service; using RepositoryT.EntityFramework; using DataAccess; using DataEntities; using RepositoryT.Infrastructure; public static class NinjectWebCommon { private static readonly Bootstrapper bootstrapper = new Bootstrapper(); /// <summary> /// Starts the application /// </summary> public static void Start() { DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule)); DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule)); bootstrapper.Initialize(CreateKernel); } /// <summary> /// Stops the application. /// </summary> public static void Stop() { bootstrapper.ShutDown(); } /// <summary> /// Creates the kernel that will manage your application. /// </summary> /// <returns>The created kernel.</returns> private static IKernel CreateKernel() { var kernel = new StandardKernel(); kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel); kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>(); RegisterServices(kernel); return kernel; } /// <summary> /// Load your modules or register your services here! /// </summary> /// <param name="kernel">The kernel.</param> private static void RegisterServices(IKernel kernel) { var factory = new DefaultDataContextFactory<TestNinjectEntities>(); kernel.Bind<IDataAccessRepository<Login>>() .To<DataAccessRepository<Login, TestNinjectEntities>>() .InRequestScope() .WithConstructorArgument("databaseFactory", factory); kernel.Bind<IUnitOfWork>() .To<UnitOfWork<TestNinjectEntities>>() .InRequestScope() .WithConstructorArgument("databaseFactory", factory); } } }