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
具体内容:
//营业相干的类
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
//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中应用:
[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);
}
}
}