簡體   English   中英

使用Autofac注入服務的實例

[英]Injecting an instance of a service with Autofac

我對Autofac注入或注冊有問題。 這是我的代碼

資料庫

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

     }

     public interface IMappingBaseRepository : IRepository<MappingBase>
     {  
     }
 }

服務

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初始化

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

現在,如果我在控制器內部,則可以毫無問題地獲得服務對象的實例。 但是我必須訪問我的服務IMappingBaseService才能從此類內的DB獲取數據:

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

任何幫助將不勝感激! 提前致謝。

代碼演示,例如:

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

也許您可以修復代碼注冊autofac,因為autofac僅注冊接口,例如:

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

解決的辦法是使用屬性注入(實例化autofac init內的類)

我們必須添加這一行

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

然后在CustomDisplayNameAttribute中添加空的構造函數

public CustomDisplayNameAttribute() {}

public IMappingBaseService _mappingBaseService { get; set; }

為了獲得對象,我們使用

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

問題是我從DisplayNameAttribute(ASP.NET MVC)附加了CustomDisplayName

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

我有這個錯誤

錯誤3屬性參數必須是屬性參數類型D:\\ CDS_ADMIN \\ ClientConfiguration.Web \\ ViewModel \\ ClientElementsViewModel.cs的常數表達式,typeof表達式或數組創建表達式22 32 ClientConfiguration.Web

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM