简体   繁体   中英

Injecting an instance of a service with Autofac

I have a problem with Autofac injection or registration. This is my code

Repository

 namespace ClientConfiguration.Data.Repository
 {
     public class MappingBaseRepository : RepositoryBase<MappingBase>, IMappingBaseRepository
     {
         public MappingBaseRepository(IDatabaseFactory databaseFactory)
                 : base(databaseFactory)
         {
         }

     }

     public interface IMappingBaseRepository : IRepository<MappingBase>
     {  
     }
 }

Service

namespace ClientConfiguration.Service {

 public interface IMappingBaseService
 {
     IEnumerable<MappingBase> GetElements(); 
     void SaveElement();
 }

 public class MappingBaseService : IMappingBaseService
 {
     private readonly IMappingBaseRepository MappingBaseRepository;
     private readonly IUnitOfWork unitOfWork;


     public MappingBaseService(IMappingBaseRepository MappingBaseRepository, IUnitOfWork unitOfWork)
     {
         this.MappingBaseRepository = MappingBaseRepository;
         this.unitOfWork = unitOfWork;
     }

     #region Members

     public IEnumerable<MappingBase> GetElements()
     {
         var Elements = MappingBaseRepository.GetAll();
         return Elements;
     }

     public void SaveElement()
     {
         unitOfWork.Commit();
     }

     #endregion
 } }

Autofac init

private static void SetAutofacContainer()  {
            var builder = new ContainerBuilder();
            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerRequest();
            builder.RegisterType<DatabaseFactory>().As<IDatabaseFactory>().InstancePerRequest();


            // Repositories
            builder.RegisterAssemblyTypes(typeof(ClientElementRepository).Assembly)
                .Where(t => t.Name.EndsWith("Repository"))
                .AsImplementedInterfaces().InstancePerRequest();

            // Services
            builder.RegisterAssemblyTypes(typeof(ClientElementService).Assembly)
               .Where(t => t.Name.EndsWith("Service"))
               .AsImplementedInterfaces().InstancePerRequest();


            IContainer container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }

Now if I'm inside a controller I have an instance of the service objects without problem. But I have to access my service IMappingBaseService to get data from DB inside this class:

namespace ClientConfiguration.Mappings {
    public class CustomDisplayNameAttribute : DisplayNameAttribute {

        private static IMappingBaseService mappingBaseService { get; set; }

        public CustomDisplayNameAttribute(string value)
            : base(GetMessageFromResource(value)) {
        }

        private static string GetMessageFromResource(string value) {

            var els = mappingBaseService.GetElements().ToList();
            //get value from DB
            //mappingBaseService is always null
            return "";
        }
    }
}

Any help would be greatly appreciated! Thanks in advance.

Code demo such as:

namespace ClientConfiguration.Mappings {
    public class CustomDisplayNameAttribute : DisplayNameAttribute {

        private static IMappingBaseService _mappingBaseService { get; set; }

        public CustomDisplayNameAttribute(string value, IMappingBaseService mappingBaseService)
            : base(GetMessageFromResource(value, mappingBaseService)) {
        }

        private static string GetMessageFromResource(string value, IMappingBaseService mappingBaseService) {
            _mappingBaseService  = mappingBaseService;
            var els = _mappingBaseService .GetElements().ToList();
            //OR var els = mappingBaseService.GetElements().ToList();
            //get value from DB
            //mappingBaseService is always null
            return "";
        }
    }
}

Maybe you can fix code register autofac, Because autofac only register for interface such as:

    builder.RegisterAssemblyTypes(typeof(IClientElementRepository).Assembly)
                .Where(t => t.Name.EndsWith("Repository"))
                .AsImplementedInterfaces().InstancePerRequest();
    // Services
            builder.RegisterAssemblyTypes(typeof(IClientElementService).Assembly)
               .Where(t => t.Name.EndsWith("Service"))
               .AsImplementedInterfaces().InstancePerRequest();

builder.RegisterAssemblyTypes(typeof(IMappingBaseService).Assembly)
               .Where(t => t.Name.EndsWith("Service"))
               .AsImplementedInterfaces().InstancePerRequest();

The solution was to use Property injection (instanciate the class inside the autofac init)

We have to add this line

builder.Register(c => new CustomDisplayNameAttribute {
_mappingBaseService = c.Resolve<IMappingBaseService>() });

and in CustomDisplayNameAttribute we add empty constructor

public CustomDisplayNameAttribute() {}

and

public IMappingBaseService _mappingBaseService { get; set; }

and for getting the object we use

var _mappingBaseService = DependencyResolver.Current.GetService<IMappingBaseService>();

The problem is that is i surcharge CustomDisplayName from DisplayNameAttribute (ASP.NET MVC)

 public class ClientElementsViewModel {
        private static IMappingBaseService _mappingBaseService;
        public ClientElementsViewModel(IMappingBaseService mappingBaseService) {
            _mappingBaseService = mappingBaseService;
        }
        [Key]
        [Display(Name = "Id")]
        public long ClientElementId { get; set; }
        [CustomDisplayName("", _mappingBaseService)]
        public string CompanyCode { get; set; }
        //[CustomDisplayName("")]
        public string WebAppBaseUrl { get; set; }
        //[CustomDisplayName("")]
        public string GuestTraveller { get; set; }
    }

I have this error

Error 3 An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type D:\\CDS_ADMIN\\ClientConfiguration.Web\\ViewModel\\ClientElementsViewModel.cs 22 32 ClientConfiguration.Web

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM