示例#1
0
        public void GivenIHaveCreatedTheEndpoint(string endpointRelativeUrl)
        {
            switch (endpointRelativeUrl)
            {
            case "/users/register":
                // Build up the options.
                IOptions <AppSettings> someOptions = Options.Create <AppSettings>(new AppSettings());

                // Setup the user mock.
                _userContext.Mock_UsersService = new MockUserService();

                // Setup the mapper.
                _userContext.Mock_Mapper = MappingProfile.InitializeAutoMapper().CreateMapper();

                // Initialise the controller.
                _userContext.Controller_Users = new Controllers.UsersController(_userContext.Mock_UsersService,
                                                                                _userContext.Mock_Mapper,
                                                                                someOptions);


                break;

            default:
                throw new NotImplementedException("The supplied endpoint is not defined in the testing steps.");
            }
        }
示例#2
0
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            var formatters = GlobalConfiguration.Configuration.Formatters;

            formatters.Remove(formatters.XmlFormatter);
            formatters.JsonFormatter.Indent = true;
            var mapper = MappingProfile.InitializeAutoMapper().CreateMapper();

            FluentValidationModelValidatorProvider.Configure(config);
            var container = new UnityContainer();

            container.RegisterType <IUnitOfWork, UnitOfWork>(new HierarchicalLifetimeManager());
            container.RegisterInstance <IMapper>(mapper);
            config.DependencyResolver = new UnityResolver(container);

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );
        }
 protected void Application_Start()
 {
     AreaRegistration.RegisterAllAreas();
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
     MappingProfile.InitializeAutoMapper();
     //ModelBinders.Binders.Add(typeof(ZetaCodeNormalIplikVmBinder), new ZetaCodeNormalIplikVmBinder());
 }
 public void TestInitialize()
 {
     _userWriteRepositoryMock = new Mock <IUserWriteRepository>();
     _userReadRepositoryMock  = new Mock <IUserReadRepository>();
     _mapper               = MappingProfile.InitializeAutoMapper().CreateMapper();
     createuserCommand     = GetCreateUserCommand();
     _createUserHandlerSut = new CreateUserHandler(_userReadRepositoryMock.Object,
                                                   _userWriteRepositoryMock.Object, _mapper);
 }
        public static IServiceCollection AddBusinessDependencies(this IServiceCollection services)
        {
            var thisAssembly = Assembly.GetExecutingAssembly();

            services.AddMediatR(thisAssembly);
            services.AddAutoMapper(thisAssembly);
            var mapper = MappingProfile.InitializeAutoMapper().CreateMapper();

            services.AddSingleton(mapper);
            return(services);
        }
示例#6
0
        public static void Configure(IUnityContainer container)
        {
            var mapper = MappingProfile.InitializeAutoMapper().CreateMapper();

            container.RegisterInstance(mapper);

            container.RegisterType <ILogger>(new InjectionFactory(l => LogManager.GetCurrentClassLogger())); // Register NLog

            container.AddNewExtension <DependencyInjectionExtension>();                                      // define dependency between BL and DL

            container.RegisterType <IEmailSender, EmailSender>();
        }
示例#7
0
        //TODO Change Automapper injection
        public static IContainer ConfigByJson(string jsonFileName)
        {
            var config = new ConfigurationBuilder();

            config.AddJsonFile(jsonFileName);
            var module  = new ConfigurationModule(config.Build());
            var builder = new ContainerBuilder();
            var mapper  = MappingProfile.InitializeAutoMapper().CreateMapper();

            builder.RegisterInstance <IMapper>(mapper);
            builder.RegisterModule(module);
            return(builder.Build());
        }
示例#8
0
    /// <summary>Integrates Unity when the application starts.</summary>
    public static void Start()
    {
        var container = UnityConfig.GetConfiguredContainer();
        var mapper    = MappingProfile.InitializeAutoMapper().CreateMapper();

        container.RegisterInstance <IMapper>(mapper);

        FilterProviders.Providers.Remove(FilterProviders.Providers.OfType <FilterAttributeFilterProvider>().First());
        FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container));

        DependencyResolver.SetResolver(new UnityDependencyResolver(container));

        // TODO: Uncomment if you want to use PerRequestLifetimeManager
        // Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
    }
示例#9
0
 public List <TasksModel> SaveAll(List <TasksModel> tasks)
 {
     try
     {
         var mapper = MappingProfile.InitializeAutoMapper().CreateMapper();
         var taskDb = mapper.Map <List <TasksModel>, List <Tasks> >(tasks);
         var result = _taskAccessor.SaveAll(taskDb);
         tasks = mapper.Map <List <Tasks>, List <TasksModel> >(result);
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
     return(tasks);
 }
        public static IUnityContainer Initialise()
        {
            var container = BuildUnityContainer();

            // mapping with automapper
            var mapper = MappingProfile.InitializeAutoMapper(typeof(Student), typeof(AddStudentRequest)).CreateMapper();

            container.RegisterInstance <IMapper>(mapper);

            var resolver = new UnityDependencyResolver(container);

            DependencyResolver.SetResolver(resolver);
            GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
            _container = container;
            return(container);
        }
示例#11
0
        public List <TasksModel> GetAll(int userId)
        {
            var tasksBs = new List <TasksModel>();

            try
            {
                var tasksDb = _taskAccessor.GetAll(userId);
                var mapper  = MappingProfile.InitializeAutoMapper().CreateMapper();
                tasksBs = mapper.Map <List <Tasks>, List <TasksModel> >(tasksDb);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return(tasksBs);
        }
示例#12
0
 public UserModel Login(UserModel user)
 {
     try
     {
         user.Password = _encryption.EncryptPassword(user.Password);
         var mapper = MappingProfile.InitializeAutoMapper().CreateMapper();
         var userDb = mapper.Map <UserModel, User>(user);
         var result = _loginAccessor.Login(userDb);
         user = mapper.Map <User, UserModel>(result);
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
     return(user);
 }
示例#13
0
        public static IContainer Initialize()
        {
            var builder = new ContainerBuilder();

            // Get your HttpConfiguration.
            var config = GlobalConfiguration.Configuration;

            // Register your Web API controllers.
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            // OPTIONAL: Register the Autofac filter provider.
            builder.RegisterWebApiFilterProvider(config);

            // OPTIONAL: Register the Autofac model binder provider.
            builder.RegisterWebApiModelBinderProvider();

            // DbContext
            builder.RegisterType(typeof(NoteOnlineContext)).As(typeof(DbContext)).InstancePerLifetimeScope();
            // Repository
            builder.RegisterModule <RepositoryModule>(); //等同(new RepositoryModule());
            // UnitOfWork
            builder.RegisterType <UnitOfWork>().As <IUnitOfWork>();
            // Service
            builder.RegisterModule <ServiceModule>();  //等同(new ServiceModule());
            // AutoMapper
            var mapper = MappingProfile.InitializeAutoMapper().CreateMapper();

            builder.RegisterInstance <IMapper>(mapper);

            builder.RegisterType <AuthorizationServerProvider>()
            .As <IOAuthAuthorizationServerProvider>()
            .PropertiesAutowired()    // to automatically resolve IUserService
            .SingleInstance();        // you only need one instance of this provider


            builder.RegisterType <ApplicationRefreshTokenProvider>()
            .As <IAuthenticationTokenProvider>()
            .SingleInstance();         // you only need one instance of this provider

            // Set the dependency resolver to be Autofac.
            var container = builder.Build();

            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            return(container);
        }
        private static IContainer RegisterServices(ContainerBuilder builder)
        {
            var cfg = new ConfigurationBuilder();

            var mapper = MappingProfile.InitializeAutoMapper().CreateMapper();

            cfg.AddJsonFile("config.json");

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            var module = new ConfigurationModule(cfg.Build());

            builder.RegisterModule(module);
            builder.RegisterInstance <IMapper>(mapper);

            Container = builder.Build();
            return(Container);
        }
示例#15
0
        public static void Register(HttpConfiguration config)
        {
            var     mapperConfig = MappingProfile.InitializeAutoMapper();
            IMapper mapper       = mapperConfig.CreateMapper();

            var container = new UnityContainer();

            container.RegisterInstance(mapper);
            //container.RegisterType<>();
            config.DependencyResolver = new UnityResolver(container);

            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );
        }
示例#16
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDefaultIdentity <IdentityUser>()
            .AddEntityFrameworkStores <PidgeonContext>()
            .AddDefaultTokenProviders();

            services.AddSignalR();

            services.AddAuthentication()
            .AddCookie()
            .AddJwtBearer(cfg =>
            {
                cfg.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                {
                    ValidIssuer      = Configuration["Tokens:Issuer"],
                    ValidAudience    = Configuration["Tokens:Audience"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"]))
                };
            });

            ConnectionString = Configuration.GetConnectionString("DefaultConnection");
            services.AddDbContext <PidgeonContext>(options => options.UseSqlServer(ConnectionString));

            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddJsonOptions(opt => opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);

            IMapper mapper = MappingProfile.InitializeAutoMapper().CreateMapper();

            services.AddSingleton(mapper);

            services.AddTransient <IDatabaseContext, DatabaseContext>();

            ResolveRepositories(services);
            ResolveServices(services);
        }
示例#17
0
        public override void Load()
        {
            this.Bind <IAuthService>().To <AuthService>();
            this.Bind <IOwinContext>()
            .ToMethod(c => HttpContext.Current.GetOwinContext())
            .WhenInjectedInto(typeof(IAuthService))
            .InRequestScope();

            this.Bind <IMapper>()
            .ToMethod(c => MappingProfile.InitializeAutoMapper().CreateMapper());

            this.Bind <IMappingProvider>().To <MappingProvider>().InRequestScope();
            this.Bind <IDateTimeProvider>().To <DateTimeProvider>().InRequestScope();
            this.Bind <IAccountManagementService>().To <AccountManagementService>().InRequestScope();
            this.Bind <ITripService>().To <TripService>().InRequestScope();
            this.Bind <ICarService>().To <CarService>().InRequestScope();
            this.Bind <ICityService>().To <CityService>().InRequestScope();
            this.Bind <ITagService>().To <TagService>().InRequestScope();
            this.Bind <IReviewService>().To <ReviewService>().InRequestScope();
            this.Bind <IReportService>().To <ReportService>().InRequestScope();
            this.Bind <IUserDashboardService>().To <UserDashboardService>().InRequestScope();
        }
示例#18
0
        /// <summary>Registers the type mappings with the Unity container.</summary>
        /// <param name="container">The unity container to configure.</param>
        /// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to
        /// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks>
        public static void RegisterTypes(IUnityContainer container)
        {
            // NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements.
            // container.LoadConfiguration();

            // TODO: Register your types here
            // container.RegisterType<IProductRepository, ProductRepository>();

            var mapper = MappingProfile.InitializeAutoMapper().CreateMapper();

            container.RegisterInstance <IMapper>(mapper);
            // register all your components with the container here
            // it is NOT necessary to register your controllers

            // e.g. container.RegisterType<ITestService, TestService>();
            container.RegisterType <DbContext, ApplicationDbContext>(new HierarchicalLifetimeManager());
            container.RegisterType <AccountController>(new InjectionConstructor());
            container.RegisterType <ISurvayService, SurvayService>();
            container.RegisterType <ISurvayTypeService, SurvayTypeService>();
            container.RegisterType <IFieldDependantService, FieldDependantService>();
            container.RegisterType <IFieldService, FieldService>();
            container.RegisterType <IFieldOptionService, FieldOptionService>();
            container.RegisterType <IOptionService, OptionService>();
            container.RegisterType <IProvinceService, ProvinceService>();
            container.RegisterType <IDistricService, DistricService>();
            container.RegisterType <ISurvaySettingService, SurvaySettingService>();
            container.RegisterType <ISurvaySupervisorService, SurvaySueprvisorService>();
            container.RegisterType <IDeviceManagerService, DeviceManagerService>();
            container.RegisterType <IAnswerSurvayService, AnswerSurvayService>();
            container.RegisterType <IClientService, ClientService>();
            container.RegisterType <IUserSurvayService, UserSurvayService>();
            container.RegisterType <IMatrixHeaderService, MatrixHeaderService>();
            container.RegisterType <IMatrixRowService, MatrixRowService>();
            container.RegisterType <IDeviceManagerService, DeviceManagerService>();

            //Data Layer dependency mapping as extension eg : IUnitOfWork
            container.AddNewExtension <DependencyInjectionExtension>();
        }
示例#19
0
        /// <summary>
        /// Registers the type mappings with the Unity container.
        /// </summary>
        /// <param name="container">The unity container to configure.</param>
        /// <remarks>
        /// There is no need to register concrete types such as controllers or
        /// API controllers (unless you want to change the defaults), as Unity
        /// allows resolving a concrete type even if it was not previously
        /// registered.
        /// </remarks>
        public static void RegisterTypes(IUnityContainer container)
        {
            // NOTE: To load from web.config uncomment the line below.
            // Make sure to add a Unity.Configuration to the using statements.
            // container.LoadConfiguration();

            // TODO: Register your type's mappings here.
            // container.RegisterType<IProductRepository, ProductRepository>();

            container.RegisterType <IItemRepository, ItemRepository>();
            container.RegisterType <ICustomerRepository, CustomerRepository>();
            container.RegisterType <ICategoryRepository, CategoryRepository>();
            container.RegisterType <IAdminRepository, AdminRepository>();
            container.RegisterType <IFileLoader, FileLoader>();
            container.RegisterType <IPaymentService, PaymentService>();
            container.RegisterType <IImportService, ImportService>();
            container.RegisterType <ICustomerAccountService, CustomerAccountService>();
            container.RegisterType <IAdminService, AdminService>();
            container.RegisterType <ICategoryService, CategoryService>();
            container.RegisterType <IItemQueryService, ItemQueryService>();
            container.RegisterType <IItemManagementService, ItemManagementService>();
            container.RegisterType <ICustomerPaymentService, CustomerPaymentService>();
            container.RegisterType <ICartService, CartService>();
            container.RegisterType <IOrderRatingRepository, OrderRatingRepository>();
            container.RegisterType <IOrderRepository, OrderRepository>();
            container.RegisterType <IDiscountRepository, DiscountRepository>();
            container.RegisterType <IOrderRatingService, OrderRatingService>();
            container.RegisterType <IDiscountManagementService, DiscountManagementService>();
            container.RegisterType <IOrderService, OrderService>();
            container.RegisterType <IPropertyService, PropertyService>();
            container.RegisterType <IPropertyRepository, PropertyRepository>();

            container.RegisterType <IEmailService, EmailService>();

            container.RegisterInstance <IMapper>(MappingProfile.InitializeAutoMapper().CreateMapper());
            container.RegisterInstance <IDbContextScopeFactory>(new DbContextScopeFactory());
            container.RegisterInstance <IAmbientDbContextLocator>(new AmbientDbContextLocator());
        }
示例#20
0
        protected void Application_Start()
        {
            var builder = new ContainerBuilder();

            var mapper_web = MappingProfile.InitializeAutoMapper().CreateMapper();

            builder.RegisterInstance(mapper_web);

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

            builder.RegisterControllers(typeof(MvcApplication).Assembly);
            builder.RegisterFilterProvider();
            builder.RegisterSource(new ViewRegistrationSource());

            builder.RegisterModule(new BlogModule());

            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
示例#21
0
        /// <summary>Registers the type mappings with the Unity container.</summary>
        /// <param name="container">The unity container to configure.</param>
        /// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to
        /// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks>
        public static void RegisterTypes(IUnityContainer container)
        {
            // NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements.
            // container.LoadConfiguration();

            var mapper = MappingProfile.InitializeAutoMapper().CreateMapper();

            // TODO: Register your types here
            // container.RegisterType<IProductRepository, ProductRepository>();
            container.RegisterType <IUserStore <User>, UserStore <User> >();
            container.RegisterType <UserManager <User> >();
            container.RegisterType <IBlogDbContext, BlogDbContext>(new PerRequestLifetimeManager());
            container.RegisterType <ManageController>(new InjectionConstructor());

            container.RegisterType <ApplicationSignInManager>();
            container.RegisterType <AccountController>(new InjectionConstructor());
            container.RegisterType <IPostRepo, PostRepo>(new PerRequestLifetimeManager());
            container.RegisterInstance <IMapper>(mapper);
            container.RegisterType <ICategoryRepo, CategoryRepo>(new PerRequestLifetimeManager());
            container.RegisterType <ICommentRepo, CommentRepo>(new PerRequestLifetimeManager());
            container.RegisterType <IReplyRepo, ReplyRepo>(new PerRequestLifetimeManager());
            container.RegisterType <IUserRepo, UserRepo>(new PerRequestLifetimeManager());
            container.RegisterType <ISettingsRepo, SettingsRepo>(new PerRequestLifetimeManager());
        }
示例#22
0
 public override void Load()
 {
     Bind <IUnitOfWork>().To <LibraryUnitOfWorkEntityFramework>()
     .WithConstructorArgument(connectionName);
     Bind <IMapper>().ToConstant(MappingProfile.InitializeAutoMapper().CreateMapper());
 }
示例#23
0
        protected override void Seed(ContextDb context)
        {
            IMapper _mapper = MappingProfile.InitializeAutoMapper().CreateMapper();

            try
            {
                IList <DocumentTypeEntity> DocumentEntityList = new List <DocumentTypeEntity>();
                var cedula = new DocumentType()
                {
                    DocumentName = "Cedula"
                };
                var cedulaExtrangeria = new DocumentType()
                {
                    DocumentName = "Cedula de extranjeria"
                };
                var tarjetaIdentidad = new DocumentType()
                {
                    DocumentName = "Tarjeta de Identidad"
                };
                var registroCivil = new DocumentType()
                {
                    DocumentName = "Registro civil"
                };
                DocumentEntityList.Add(_mapper.Map <DocumentTypeEntity>(cedula));
                DocumentEntityList.Add(_mapper.Map <DocumentTypeEntity>(cedulaExtrangeria));
                DocumentEntityList.Add(_mapper.Map <DocumentTypeEntity>(tarjetaIdentidad));
                DocumentEntityList.Add(_mapper.Map <DocumentTypeEntity>(registroCivil));

                context.DocumentTypes.AddRange(DocumentEntityList);
                context.SaveChanges();

                IList <AppointmentTypeEntity> AppointmentEntityList = new List <AppointmentTypeEntity>();
                var medGen = new AppointmentType()
                {
                    AppointMentName = "Medeicina General"
                };
                var odont = new AppointmentType()
                {
                    AppointMentName = "Odontologia"
                };
                var ped = new AppointmentType()
                {
                    AppointMentName = "Pediatria"
                };
                var neuro = new AppointmentType()
                {
                    AppointMentName = "Neurologia"
                };
                AppointmentEntityList.Add(_mapper.Map <AppointmentTypeEntity>(medGen));
                AppointmentEntityList.Add(_mapper.Map <AppointmentTypeEntity>(odont));
                AppointmentEntityList.Add(_mapper.Map <AppointmentTypeEntity>(ped));
                AppointmentEntityList.Add(_mapper.Map <AppointmentTypeEntity>(neuro));

                context.AppointmentTypes.AddRange(AppointmentEntityList);
                context.SaveChanges();

                IList <PatientEntity> PatientsEntityList = new List <PatientEntity>();
                var patient1 = new Patient()
                {
                    Document = "1065584866", DocumentTypeId = DocumentEntityList.FirstOrDefault(x => x.DocumentName == "Cedula").Id, FirstName = "Alvaro Jose", LastName = "Julio Beltran", PhoneNumber = "3193745954", Email = "*****@*****.**", BirthDay = new DateTime(1987, 7, 7)
                };
                var patient2 = new Patient()
                {
                    Document = "10655823840", DocumentTypeId = DocumentEntityList.FirstOrDefault(x => x.DocumentName == "Cedula").Id, FirstName = "Eilen Melissa", LastName = "Beltran Colon", PhoneNumber = "3173745957", Email = "*****@*****.**", BirthDay = new DateTime(1990, 12, 23)
                };
                var patient3 = new Patient()
                {
                    Document = "1065584899", DocumentTypeId = DocumentEntityList.FirstOrDefault(x => x.DocumentName == "Cedula").Id, FirstName = "Natali Andre", LastName = "Julio Beltran", PhoneNumber = "3133745959", Email = "*****@*****.**", BirthDay = new DateTime(1998, 5, 15)
                };
                PatientsEntityList.Add(_mapper.Map <PatientEntity>(patient1));
                PatientsEntityList.Add(_mapper.Map <PatientEntity>(patient2));
                PatientsEntityList.Add(_mapper.Map <PatientEntity>(patient3));

                context.Patients.AddRange(PatientsEntityList);
                context.SaveChanges();
            }
            catch (Exception ex)
            {
                throw new DbUpdateException("Error con la base de datos: " + ex);
            }
        }
示例#24
0
        public LocatorViewModel()
        {
            var builder = new ContainerBuilder();

            // View models, Autofac will register concrete classes as multi-instance.
            builder.RegisterAssemblyTypes(this.GetType().Assembly)
            .Where(t =>
                   t.Name.EndsWith("ViewModel") &&
                   t.Name != "LocatorViewModel" &&
                   t.Name != "BaseViewModel")
            .PropertiesAutowired()
            .AsSelf();

            // Services, Autofac will register interface.
            var services = new[] { "DialogService", "SettingsService", "NavigationService" };

            builder.RegisterAssemblyTypes(this.GetType().Assembly)
            .Where(t =>
                   t.Name.EndsWith("Service") &&
                   !services.Any(e => t.Name.Equals(e)))
            .AsImplementedInterfaces()
            .PropertiesAutowired();

            // Services, Singleton
            builder.RegisterAssemblyTypes(this.GetType().Assembly)
            .Where(t => services.Any(e => t.Name.Equals(e)))
            .AsImplementedInterfaces()
            .PropertiesAutowired()
            .SingleInstance();

            // Repository, Autofac will register interface.
            var repositories = new[] { "RestRepository" };

            builder.RegisterAssemblyTypes(this.GetType().Assembly)
            .Where(t =>
                   t.Name.EndsWith("Repository") &&
                   !repositories.Any(e => t.Name.Equals(e)))
            .AsImplementedInterfaces()
            .PropertiesAutowired();

            // Repository, Singleton
            builder.RegisterAssemblyTypes(this.GetType().Assembly)
            .Where(t => repositories.Any(e => t.Name.Equals(e)))
            .AsImplementedInterfaces()
            .PropertiesAutowired()
            .SingleInstance();

            // Automapper
            var mapper = MappingProfile.InitializeAutoMapper().CreateMapper();

            builder.RegisterInstance <IMapper>(mapper);

            // DataBase
            builder.Register(c => new SQLiteAsyncConnection(FilePathDb))
            .AsSelf()
            .SingleInstance();

            _container?.Dispose();

            _container = builder.Build();
        }
示例#25
0
        public void Init()
        {
            var mapperConfig = MappingProfile.InitializeAutoMapper();

            mapper = mapperConfig.CreateMapper();
        }