一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](七) (2)

再精简并修改 PostService.cs:

using TsBlog.Domain.Entities; using TsBlog.Repositories; namespace TsBlog.Services { public class PostService : GenericService<Post>, IPostService { private readonly IPostRepository _repository; public PostService(IPostRepository repository) : base(repository) { _repository = repository; } } }

重新编译并按F5运行 【TsBlog.Frontend】Web应用程序,你会看到如下的错误提示:

create-aspnet-mvc-5-web-application-repository-autofac-automapper-sqlsugar-step-by-step-07-01.png

这是为什么呢?是因为我们之前写好的 PostRepository.cs类中没有继承IPostRepository接口,但我们在 PostService.cs 类中使用了非泛型的 IPostRepository接口,所以在 PostRepository.cs 类中添加 IPostRepository 的接口,此时的 PostRepository.cs :

using TsBlog.Domain.Entities; namespace TsBlog.Repositories { /// <summary> /// POST表的数据库操作类 /// </summary> public class PostRepository : GenericRepository<Post>, IPostRepository { } }

最终的 Global.asax.cs :

using Autofac; using Autofac.Features.ResolveAnything; using Autofac.Integration.Mvc; using System; using System.Linq; using System.Web.Mvc; using System.Web.Routing; using TsBlog.AutoMapperConfig; using TsBlog.Repositories; namespace TsBlog.Frontend { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); //BundleConfig.RegisterBundles(BundleTable.Bundles); AutofacRegister(); AutoMapperRegister(); } private void AutofacRegister() { var builder = new ContainerBuilder(); //注册MvcApplication程序集中所有的控制器 builder.RegisterControllers(typeof(MvcApplication).Assembly); //注册仓储层服务 //builder.RegisterType<PostRepository>().As<IPostRepository>(); //注册基于接口约束的实体 var assembly = AppDomain.CurrentDomain.GetAssemblies(); builder.RegisterAssemblyTypes(assembly) .Where( t => t.GetInterfaces() .Any(i => i.IsAssignableFrom(typeof(IDependency))) ) .AsImplementedInterfaces() .InstancePerDependency(); //builder.RegisterGeneric(typeof(GenericRepository<>)) // .As(typeof(IRepository<>)); //builder.RegisterGeneric(typeof(GenericService<>)) // .As(typeof(IService<>)); //builder.RegisterGeneric(typeof(GenericRepository<>)); //builder.RegisterGeneric(typeof(GenericService<>)); //注册服务层服务 //builder.RegisterType<PostService>().As<IPostService>(); //注册过滤器 builder.RegisterFilterProvider(); builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource()); var container = builder.Build(); //设置依赖注入解析器 DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); } /// <summary> /// AutoMapper的配置初始化 /// </summary> private void AutoMapperRegister() { new AutoMapperStartupTask().Execute(); } } }

再次按F5运行,打开页面[:54739/home/post ],页面又回来了,哈哈。。。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpfdpj.html