本文整理汇总了C#中Autofac.ContainerBuilder.RegisterModule方法的典型用法代码示例。如果您正苦于以下问题:C# ContainerBuilder.RegisterModule方法的具体用法?C# ContainerBuilder.RegisterModule怎么用?C# ContainerBuilder.RegisterModule使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Autofac.ContainerBuilder
的用法示例。
在下文中一共展示了ContainerBuilder.RegisterModule方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Application_Start
protected void Application_Start()
{
log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(@"../../../log4net.xml"));
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterModule(new BusConfigModule());
// use raven
builder.RegisterModule(new RavenConfigModule());
// or use nhibernate
// builder.RegisterModule(new NHibernateConfigModule());
builder.RegisterControllers(Assembly.GetExecutingAssembly());
containerProvider = new ContainerProvider(builder.Build());
DependencyResolver.SetResolver(new AutofacDependencyResolver(containerProvider.ApplicationContainer));
}
示例2: Setup
public static void Setup()
{
var builder = new ContainerBuilder();
builder.RegisterControllers(Assembly.GetExecutingAssembly());
// Register for API Controllers
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterModelBinders(Assembly.GetExecutingAssembly());
builder.RegisterFilterProvider();
builder.RegisterModelBinderProvider();
builder.RegisterModule<AutofacWebTypesModule>();
// Find all autofac modules and include them.
builder.RegisterModule<IdentityModule>();
// Find all IStartable tasks and register them.
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
builder.RegisterAssemblyTypes(assemblies)
.AssignableTo<IStartable>()
.As<IStartable>()
.SingleInstance();
// Enable property injection into action filters (including authorize attribute).
builder.RegisterFilterProvider();
IContainer container = builder.Build();
var resolver = new AutofacWebApiDependencyResolver(container);
GlobalConfiguration.Configuration.DependencyResolver = resolver;
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
示例3: Application_Start
protected void Application_Start(object sender, EventArgs e)
{
var builder = new ContainerBuilder();
builder.RegisterModelBinders(Assembly.GetExecutingAssembly());
builder.RegisterModelBinderProvider();
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.RegisterType<AuthenticationService>().As<IAuthenticationService>();
builder.RegisterModule<AutofacWebTypesModule>();
builder.RegisterModule<NHibernateModule>();
// Change controller action parameter injection by changing web.config.
builder.RegisterType<ExtensibleActionInvoker>().As<IActionInvoker>().InstancePerHttpRequest();
// MVC integration test items
builder.RegisterType<InvokerDependency>().As<IInvokerDependency>();
// DomainServices
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).AssignableTo<DomainService>();
builder.RegisterModule<AutofacDomainServiceModule>();
IContainer container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
DomainService.Factory = new AutofacDomainServiceFactory(new MvcContainerProvider());
RegisterRoutes(RouteTable.Routes);
}
示例4: CreateContainer
/// <summary>
/// Creates the DI container for the application.
/// </summary>
/// <param name="context">The application context that controls when the application will terminate.</param>
/// <param name="storageDirectory">The directory in which all the uploaded files are stored.</param>
/// <returns>The DI container.</returns>
public static IContainer CreateContainer(ApplicationContext context, string storageDirectory)
{
var builder = new ContainerBuilder();
{
builder.RegisterInstance(context)
.As<ApplicationContext>()
.ExternallyOwned()
.SingleInstance();
builder.RegisterModule(new UtilitiesModule());
builder.RegisterModule(
new CommunicationModule(
new List<CommunicationSubject>
{
CommunicationSubjects.TestTransfer,
CommunicationSubjects.TestExecution,
},
new List<ChannelType>
{
ChannelType.NamedPipe,
ChannelType.TcpIP,
},
true));
RegisterFileSystem(builder);
RegisterReports(builder);
RegisterInformation(builder);
RegisterNotifications(builder);
RegisterCommands(builder, storageDirectory);
}
return builder.Build();
}
示例5: InMemory_Request_Retrieve_Mock_Test
public void InMemory_Request_Retrieve_Mock_Test()
{
var builder = new ContainerBuilder();
builder.RegisterModule<ProcessingConsumerModule>();
builder.RegisterModule<BillingConsumerModule>();
builder.RegisterModule<UserManagementConsumerModule>();
var itemList = new List<Item>();
itemList.Add(new Item { Info = "mockResponse" });
var mockItemRepository = new Mock<IRepository<Item>>();
mockItemRepository.Setup(rep =>
rep.Query(It.IsAny<Expression<Func<Item, bool>>>()))
.Returns(itemList.AsQueryable());
builder.Register(c =>
mockItemRepository.Object).As<IRepository<Item>>();
using (var service = Service.InMemory(builder).Start())
{
var msg = new RequestItemMessage("mockSelection");
var client = service.CreateRequestClient<RequestItem, ItemResponse>();
var response = client.Request(msg).Result;
Assert.AreEqual("mockResponse", response.ItemInfo);
}
}
示例6: BuildContainer
private IContainer BuildContainer()
{
// Use 'InstancePerLifetimeScope' to create instance which will be shared during the consuming of one message
var builder = new ContainerBuilder();
builder.RegisterModule(new ServiceBusModule());
builder.RegisterModule(new TranslationServiceModule());
builder.RegisterModule(new MailerModule());
// Register razor mail message factory (have not found a way to put this in a module, due to the dependencyResolver parameter)
builder.RegisterType<RazorMailMessageFactory>()
.WithParameter(new NamedParameter("templateResolver", new DefaultTemplateResolver("Infrastructure", "TemplateMailMessages")))
.WithParameter(new NamedParameter("templateBase", typeof(ViewBaseClass<>)))
.WithParameter(new NamedParameter("dependencyResolver", new Func<Type, object>(x => _container.Resolve(x))))
.WithParameter(new NamedParameter("templateCache", new InMemoryTemplateCache()))
.As<IRazorMailMessageFactory>()
.InstancePerLifetimeScope();
builder.Register(c => NHibernateHelper.SessionFactory).SingleInstance();
builder.Register(c => c.Resolve<ISessionFactory>().OpenSession()).As<ISession>().InstancePerLifetimeScope();
builder.RegisterType<InMemoryKeyValueCache>().As<IKeyValueCache>().InstancePerLifetimeScope();
builder.RegisterType<TranslationRepository>().As<ITranslationRepository>().InstancePerLifetimeScope();
builder.RegisterType<ApplicationSettings>().As<IApplicationSettings>().SingleInstance();
builder.RegisterType<NLogLogger>().As<ILogger>().InstancePerLifetimeScope();
return builder.Build();
}
示例7: Initialize
public static IContainer Initialize(ContainerBuilder builder, HttpConfiguration config)
{
// Register all controllers
builder.RegisterApiControllers(typeof(Startup).Assembly);
// Register Autofac filter provider
builder.RegisterWebApiFilterProvider(config);
// Register model binders
builder.RegisterWebApiModelBinderProvider();
// Register all Autofac specific IModule implementations
builder.RegisterAssemblyModules(typeof(Startup).Assembly);
builder.RegisterAssemblyModules(typeof(AutofacMediator).Assembly);
builder.RegisterModule(new RequestHandlerModule());
builder.RegisterModule(new EntityFrameworkModule());
builder.RegisterModule(new DocumentGeneratorModule());
// http://www.talksharp.com/configuring-autofac-to-work-with-the-aspnet-identity-framework-in-mvc-5
builder.RegisterType<IwsIdentityContext>().AsSelf().InstancePerRequest();
builder.RegisterType<ApplicationUserStore>().As<IUserStore<ApplicationUser>>().InstancePerRequest();
builder.RegisterType<ApplicationUserManager>().AsSelf().InstancePerRequest();
builder.RegisterType<ApplicationUserManager>().As<UserManager<ApplicationUser>>().InstancePerRequest();
return builder.Build();
}
示例8: Load
protected override void Load(ContainerBuilder builder)
{
builder.RegisterModule(new LogModule());
builder.RegisterModule(new SecurityModule());
builder.Register(c => new GZipFilter()).Keyed<IMessageFilter>(ZipMode.GZip).SingleInstance();
builder.Register(c => new RSACryptoFilter()).Keyed<IMessageFilter>(CryptoMode.RSA).SingleInstance();
builder.Register(c => new Crc32Filter()).Keyed<IMessageFilter>(ChecksumMode.Crc32).SingleInstance();
builder.Register(c => new MessageFilterFactory()).AsSelf().SingleInstance();
builder.Register(c => new Json()).Keyed<ISerializer>(SerializeMode.Json).SingleInstance();
builder.Register(c => new Protobuf()).Keyed<ISerializer>(SerializeMode.Protobuf).SingleInstance();
builder.Register(c => new ExceptionCounterFilter()).AsSelf().SingleInstance();
builder.Register(c => new CommandHandler(c.Resolve<TimeoutNotifyProducerConsumer<AbstractAsyncCommand>>())).AsSelf().SingleInstance();
builder.Register(c => new DuplexMessageWriterImplV1()).Keyed<IMessageWriter<DuplexMessage>>(MessageVersion.V1).SingleInstance();
builder.Register(c => new DuplexMessageReaderImplV1()).Keyed<IMessageReader<DuplexMessage>>(MessageVersion.V1).SingleInstance();
builder.RegisterType<TimeoutNotifyProducerConsumer<AbstractAsyncCommand>>()
.WithParameter(new NamedParameter("capacity", AbstractAsyncCommand.BLOCK_UNTIL_TIMEOUT_QUEUE_CAPACITY))
.AsSelf()
.SingleInstance()
.OnActivated(o =>
{
o.Instance.OnConsume += (sender, e) =>
{
var consumingItem = e.ConsumingItem as ChunkedConsumingItem<AbstractAsyncCommand>;
if (consumingItem == null) return;
foreach (var item in consumingItem.Chunk)
{
try
{
item.RunAsync();
}
catch (Exception) { }
}
};
});
}
示例9: SetupContainer
private static void SetupContainer()
{
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<Logger>().As<ILogger>();
builder.RegisterType<AutofacServiceProvider>()
.As<Xdore.Core.IServiceProvider>()
.InstancePerLifetimeScope();
#region Modules
builder.RegisterModule<AutofacWebTypesModule>();
builder.RegisterModule<DataAccessRegistrationModule>();
builder.RegisterModule<ServicesRegistrationModule>();
#endregion
builder.RegisterControllers(Assembly.GetExecutingAssembly())
.PropertiesAutowired();
builder.RegisterFilterProvider();
IContainer container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
ServiceLocator.Initialize(() =>
{
return DependencyResolver.Current.GetService<IServiceProvider>();
});
IDbContextFactory dbFactory = DependencyResolver.Current.GetService<IDbContextFactory>();
dbFactory.InitDbContext();
}
示例10: Setup
public static void Setup()
{
var builder = new ContainerBuilder();
// Register controllers
builder.RegisterControllers(typeof(MvcApplication).Assembly);
// Register modules
builder.RegisterModule(new ServiceBusModule());
builder.RegisterModule(new NHibernateSessionModule());
builder.RegisterModule(new TranslationServiceModule());
builder.RegisterModule(new LoggerModule());
// Register types
builder.RegisterType<ApplicationSettings>().As<IApplicationSettings>().SingleInstance();
builder.RegisterType<InMemoryKeyValueCache>().As<IKeyValueCache>().SingleInstance();
builder.RegisterType<TranslationRepository>().As<ITranslationRepository>();
builder.RegisterType<UserRepository>().As<IUserRepository>();
builder.RegisterType<LogRepository>().As<ILogRepository>();
builder.RegisterType<DefaultEncryptor>().As<IEncryptor>();
builder.RegisterType<CultureService>().As<ICultureService>();
builder.Register(c => new RegularExpressionPasswordPolicy(c.Resolve<IApplicationSettings>().PasswordPolicy)).As<IPasswordPolicy>();
Container = builder.Build();
// Enables autofac to resolve controllers instead of default asp.net mvc implementation
DependencyResolver.SetResolver(new AutofacDependencyResolver(Container));
}
示例11: Application_Start
protected void Application_Start()
{
SessionScope.SetSessionScopeService(new WebSessionScopeService());
RequestScope.SetRequestScopeService(new WebRequestScopeService());
var builder = new ContainerBuilder();
builder.RegisterModule<ServiceModule>();
builder.RegisterModule<DomainModule>();
builder.RegisterModule<QueryModelModule>();
builder.Register(a => new AutofacDependencyResolver(() => CurrentLifetimeScope, DependencyResolver.Current))
.As<IDependencyResolver>()
.SingleInstance();
builder.RegisterType<AutofacControllerFactory>().As<IControllerFactory>().SingleInstance();
builder.RegisterType<DotLessCompiler>().AsSelf().SingleInstance();
RegisterComponents(builder);
_container = builder.Build();
CurrentLifetimeScope = _container.BeginLifetimeScope();
DependencyResolver.SetResolver(_container.Resolve<IDependencyResolver>());
RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
RouteTable.Routes.MapRoute("Login", "login", new { controller = "account", action = "login" });
RouteTable.Routes.MapRoute("Default", "{controller}/{action}/{id}",
new {controller = "Dashboard", action = "Index",
id = UrlParameter.Optional});
}
示例12: Load
protected override void Load(ContainerBuilder builder)
{
// Specific registrations and initialization:
Plugins.SetInitializationLogging(DeploymentUtility.InitializationLogProvider);
if (_deploymentTime)
{
builder.RegisterModule(new DatabaseGeneratorModuleConfiguration(_shortTransaction));
builder.RegisterType<DataMigration>();
builder.RegisterType<DatabaseCleaner>();
builder.RegisterType<ApplicationGenerator>();
Plugins.FindAndRegisterPlugins<IGenerator>(builder);
}
else
{
builder.RegisterType<ApplicationInitialization>();
Plugins.FindAndRegisterPlugins<IServerInitializer>(builder);
}
// General registrations:
builder.RegisterModule(new Rhetos.Configuration.Autofac.DefaultAutofacConfiguration(_deploymentTime, _deployDatabaseOnly));
// Specific registrations override:
builder.RegisterType<ProcessUserInfo>().As<IUserInfo>();
builder.RegisterInstance(DeploymentUtility.InitializationLogProvider).As<ILogProvider>(); // InitializationLogProvider allows overriding deployment logging (both within and outside IoC).
base.Load(builder);
}
示例13: Application_Start
void Application_Start(object sender, EventArgs e)
{
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new RazorViewEngine());
GlobalConfiguration.Configure(WebApiConfig.Register);
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
BaseFrontendMappings.Initialize();
InitializerModule.InitializeDb();
AddTask("RemoveUsers", 3600);
var config = GlobalConfiguration.Configuration;
//Autofac Configuration
var builder = new ContainerBuilder();
builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterModule(new MapperModule());
builder.RegisterModule(new RepositoryModule());
builder.RegisterModule(new ContractModule());
builder.RegisterModule(new EfModule());
builder.RegisterModule(new BaseFrontendModule());
var container = builder.Build();
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
示例14: verify_usage_across_multiple_registration_modules
public void verify_usage_across_multiple_registration_modules()
{
var module1 = new SimplePipelineModule(item =>
{
item.RegisterPipeline<MultipipelineTests.In, MultipipelineTests.Out>()
.Bind<MultipipelineTests.InOutTranslator>();
item.RegisterPipeline<string, int, string>("foo")
.Bind(p => (p * 3).ToString());
});
var module2 = new SimplePipelineModule(item => item.RegisterPipeline<int, string>()
.Bind(p => (p * 2).ToString()));
var builder = new ContainerBuilder();
builder.RegisterModule(module1);
builder.RegisterModule(module2);
var ctx = builder.Build();
var value1 = ctx.Resolve<Functor<MultipipelineTests.In, MultipipelineTests.Out>>()(new MultipipelineTests.In()).NewValue;
var value2 = ctx.Resolve<Functor<int, string>>()(10);
var value3 = ctx.Resolve<Functor<string, int, string>>()("foo", 10);
Assert.That(value1, Is.EqualTo(20));
Assert.That(value2, Is.EqualTo("20"));
Assert.That(value3, Is.EqualTo("30"));
}
示例15: RegisterModules
private static IContainer RegisterModules()
{
var builder = new ContainerBuilder();
builder.RegisterModule<WebApi>();
builder.RegisterModule<ServiceArchCore>();
return builder.Build();
}