1

リポジトリパターンとAutofac依存性注入を使用してC#MVC Webアプリケーションを構築しました。データベースについては、MongoDBをデータベースとして使用しています。 リポジトリパターンと依存性注入(Autofac)を使用したC#

は、私が今直面している私のコードとエラーを確認するために助けが必要:タイプ 「ErpWebApp.Services上 「Autofac.Core.Activators.Reflection.DefaultConstructorFinder」で見つかったコンストラクタの

なし。 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の

012です
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> 
+0

はあなたがアプリケーションの設定(web.configファイル)を投稿することができますか? –

+0

@Ephraim web.configが追加されました。 – Gerry

答えて

2

AccountServicesIDbRepository<AccountCategories>を入力期待。しかし、あなたはDBRepository<AccountCategories>を登録している:

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

それとも:またBのケーシングの間異なること

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

ノート代わりに

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

は、あなたがその行を変更する必要がありますIDbRepositoryおよびDBRepositoryが混乱しています。

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

+0

ありがとうございます!私は今、ラインを変更した後、アプリケーションを実行し、インターフェイスからすべてのメソッドを実装することができます。 – Gerry

0

あなたはタイプ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. 
関連する問題