C#with repository pattern and dependency injection(Autofac)

时间:2016-04-30 06:20:46

标签: c# asp.net-mvc mongodb dependency-injection repository-pattern

我开始构建一个带有存储库模式和Autofac依赖注入的C#MVC Web应用程序。对于数据库,我使用MongoDB作为数据库。

我需要帮助来查看我现在遇到的代码和错误:

  

没有找到的构造函数   类型上的'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'   可以使用调用'ErpWebApp.Services.Implementer.AccountServices'   可用的服务和参数:无法解析参数   'ErpWebApp.Domain.IDbRepository 1[ErpWebApp.Domain.Entities.AccountCategories] accCategoriesRepository' of constructor 'Void .ctor(ErpWebApp.Domain.IDbRepository 1 [ErpWebApp.Domain.Entities.AccountCategories])'

我的代码详情如下,如果需要任何其他信息,请告诉我。

这是我的实体

public interface IEntityBase<TId>
{
    TId Id { get; set; }
}

public interface IAuditBase : IEntityBase<ObjectId>
{
    bool IsActive { get; set; }
    string CreatedBy { get; set; }
    BsonDateTime CreatedTime { get; set; }
    string ModifiedBy { get; set; }
    BsonDateTime ModifiedTime { get; set; }
}

public class AccountCategories : IAuditBase
{
    public AccountCategories()
    {
        IsActive = true;
        CreatedTime = DateTime.UtcNow;
        ModifiedTime = DateTime.UtcNow;
    }

    #region Inherit
    [BsonId]
    public ObjectId Id { get; set; }

    public bool IsActive { get; set; }
    public string CreatedBy { get; set; }
    public BsonDateTime CreatedTime { get; set; }
    public string ModifiedBy { get; set; }
    public BsonDateTime ModifiedTime { get; set; }
    #endregion

    #region Member
    public string Name { get; set; }
    #endregion

}

这是我的存储库

public interface IDbRepository<T> where T: class
{
    IMongoDatabase _database { get; }
    IMongoCollection<T> _collection { get; }

    IEnumerable<T> List { get; }

    Task<IEnumerable<T>> GetAllAsync();
    //Task<T> GetOneAsync(T context);
    //Task<T> GetOneAsync(string id);
}

public class DbRepository<T> where T : IAuditBase 
{
    public static IMongoDatabase _database;
    public static IMongoCollection<T> _collection;

    public DbRepository()
    {
        GetDatabase();
        GetCollection();
    }

    private void GetDatabase()
    {
        var _dbName = ConfigurationManager.AppSettings["MongoDbDatabaseName"];
        var _connectionString = ConfigurationManager.AppSettings["MongoDbConnectionString"];

        _connectionString = _connectionString.Replace("{DB_NAME}", _dbName);

        var client = new MongoClient(_connectionString);
        _database = client.GetDatabase(_dbName);
    }

    private void GetCollection()
    {
        _collection = _database.GetCollection<T>(typeof(T).Name);
    }

    private MongoCollectionBase<T> GetCollection<T>()
    {
        var _result = _database.GetCollection<T>(typeof(T).Name) as MongoCollectionBase<T>;

        return _result;
    }

    public IEnumerable<T> List()
    {
        var _result = GetCollection<T>().AsQueryable<T>().ToList(); ;

        return _result;
    }

    public async Task<IEnumerable<T>> GetAllAsync(IMongoCollection<T> collection)
    {
        return await collection.Find(f => true).ToListAsync();
    }

这是我的服务

public interface IAccountServices
{
    IEnumerable<AccountCategories> GetAll();
}

public class AccountServices :IAccountServices
{
    private readonly IDbRepository<AccountCategories> _accCategoriesRepository;

    public AccountServices(IDbRepository<AccountCategories> accCategoriesRepository)
    {
        _accCategoriesRepository = accCategoriesRepository;
    }

    public IEnumerable<AccountCategories> GetAll()
    {
        var _result = _accCategoriesRepository.GetAllAsync().Result;

        return _result;
    }
}

这是我的助手类

public interface IAccountHelper
{
    DataTableResult GetData(DataTableParameters param);
}

public class AccountHelper : IAccountHelper
{
    private readonly IAccountServices _accountService;

    public AccountHelper(IAccountServices accountServices)
    {
        _accountService = accountServices;
    }

    public DataTableResult GetData(DataTableParameters param)
    {
        int totalRecords = 0;

        var data = _accountService.GetAll();

        int totalDisplayRecords = data.Count();
        totalRecords = totalDisplayRecords;

        // testing
        return new DataTableResult()
        {
            aaData = null, 
            iTotalDisplayRecords = 0,
            iTotalRecords = 0
        };

    }
}

这是我的控制器

public class AccountController : Controller
{
    private readonly IAccountHelper _helper;
    // GET: UserTypes
    public AccountController(IAccountHelper helper)
    {
        _helper = helper;
    }
    // GET: Account
    public ActionResult Index()
    {
        return View();
    }

    public JsonResult Get(DataTableParameters param)
    {
        var data = _helper.GetData(param);
        return Json(data, JsonRequestBehavior.AllowGet);
    }
}

这是我的AutoFac

public class DependencyInjectionConfig
{
    public static IContainer Build()
    {
        var builder = new ContainerBuilder();
        builder.RegisterFilterProvider();

        builder.RegisterControllers(typeof(MvcApplication).Assembly);

        builder.RegisterGeneric(typeof(DbRepository<>)).As(typeof(DbRepository<>));

        //Service
        builder.RegisterType<AccountServices>().As<IAccountServices>();

        //Helpers
        builder.RegisterType<AccountHelper>().As<IAccountHelper>();

        return builder.Build();
    }
}

Global.asax中

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    var container = DependencyInjectionConfig.Build();

    DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}

的Web.config

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=301880
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-ErpWebApp.UI-20160406113616.mdf;Initial Catalog=aspnet-ErpWebApp.UI-20160406113616;Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />

    <add key="MongoDbDatabaseName" value="ERP-Apps-Dev" />
    <add key="MongoDbConnectionString" value="mongodb://localhost:27017/{DB_NAME}" />
  </appSettings>
  <system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1" />
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
    </httpModules>
  </system.web>
  <system.webServer>
    <modules>
      <remove name="FormsAuthentication" />
      <remove name="ApplicationInsightsWebTracking" />
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
    </modules>
    <validation validateIntegratedModeConfiguration="false" />
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Autofac" publicKeyToken="17863af14b0044da" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.5.0.0" newVersion="3.5.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
</configuration>

2 个答案:

答案 0 :(得分:2)

AccountServices期望类型IDbRepository<AccountCategories>。但您已注册DBRepository<AccountCategories>

builder.RegisterGeneric(typeof(DBRepository<>)).As(typeof(DBRepository<>));

相反,您应该将该行更改为:

builder.RegisterGeneric(typeof(DBRepository<>)).As(typeof(IDbRepository<>));

或者也许:

builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())
            .AsClosedTypesOf(typeof(IDbRepository<>), true)
            .AsImplementedInterfaces();
  

另请注意,BIDbRepository之间的DBRepository大小不一,这令人困惑。

答案 1 :(得分:0)

builder.RegisterType<AccountServices>().As<IAccountServices>();

您正在注册类型AccountServices,但是该类没有实现无参数构造函数,因此期望在内部传递内容。

您可以使用WithParameter ......

builder.RegisterType<AccountServices>().As<IAccountServices>().WithParameter("accCategoriesRepository", IDbRepository); 
// Where IDbReporsitory is the value of your parameter. Replace this with what you actually want to register.
相关问题