Gerry Gry
Gerry Gry

Reputation: 182

C# with repository pattern and dependency injection (Autofac)

I started to build a C# MVC web application with repository pattern and Autofac dependency injection. For database, I'm using MongoDB as database.

I need help to review my code and error that I faced now :

None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'ErpWebApp.Services.Implementer.AccountServices' can be invoked with the available services and parameters: Cannot resolve parameter 'ErpWebApp.Domain.IDbRepository1[ErpWebApp.Domain.Entities.AccountCategories] accCategoriesRepository' of constructor 'Void .ctor(ErpWebApp.Domain.IDbRepository1[ErpWebApp.Domain.Entities.AccountCategories])'.

Details of my code as below, please let me know if any other information needed.

This is my Entities

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

}

This is my Repository

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();
    }

This is my Services

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;
    }
}

This is my Helper class

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
        };

    }
}

This is my controller

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);
    }
}

This is my 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>

Upvotes: 1

Views: 3171

Answers (2)

NightOwl888
NightOwl888

Reputation: 56869

AccountServices expects type IDbRepository<AccountCategories>. But you have registered DBRepository<AccountCategories>:

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

Instead, you should change that line to:

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

Or perhaps:

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

Note also that the casing of B differs between IDbRepository and DBRepository, which is confusing.

Upvotes: 2

jegtugado
jegtugado

Reputation: 5141

On

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

You are registering type AccountServices but the said class doesn't implement a parameterless constructor so it is expecting something to be passed inside.

You can use WithParameter for this...

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.

Upvotes: 0

Related Questions