本文整理汇总了C#中Autofac.ContainerBuilder.Build方法的典型用法代码示例。如果您正苦于以下问题:C# ContainerBuilder.Build方法的具体用法?C# ContainerBuilder.Build怎么用?C# ContainerBuilder.Build使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Autofac.ContainerBuilder
的用法示例。
在下文中一共展示了ContainerBuilder.Build方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Init
public void Init() {
_settingsA = new ShellSettings { Name = "Alpha" };
_settingsB = new ShellSettings { Name = "Beta", };
_routes = new RouteCollection();
var rootBuilder = new ContainerBuilder();
rootBuilder.Register(ctx => _routes);
rootBuilder.RegisterType<ShellRoute>().InstancePerDependency();
rootBuilder.RegisterType<RunningShellTable>().As<IRunningShellTable>().SingleInstance();
rootBuilder.RegisterModule(new WorkContextModule());
rootBuilder.RegisterType<WorkContextAccessor>().As<IWorkContextAccessor>().InstancePerMatchingLifetimeScope("shell");
rootBuilder.RegisterType<HttpContextAccessor>().As<IHttpContextAccessor>();
rootBuilder.RegisterType<ExtensionManager>().As<IExtensionManager>();
rootBuilder.RegisterType<StubCacheManager>().As<ICacheManager>();
rootBuilder.RegisterType<StubAsyncTokenProvider>().As<IAsyncTokenProvider>();
rootBuilder.RegisterType<StubParallelCacheContext>().As<IParallelCacheContext>();
_rootContainer = rootBuilder.Build();
_containerA = _rootContainer.BeginLifetimeScope(
"shell",
builder => {
builder.Register(ctx => _settingsA);
builder.RegisterType<RoutePublisher>().As<IRoutePublisher>().InstancePerMatchingLifetimeScope("shell");
});
_containerB = _rootContainer.BeginLifetimeScope(
"shell",
builder => {
builder.Register(ctx => _settingsB);
builder.RegisterType<RoutePublisher>().As<IRoutePublisher>().InstancePerMatchingLifetimeScope("shell");
});
}
示例2: SetIocContainer
private static void SetIocContainer()
{
//Implement Autofac
var configuration = GlobalConfiguration.Configuration;
var builder = new ContainerBuilder();
// Register MVC controllers using assembly scanning.
builder.RegisterControllers(Assembly.GetExecutingAssembly());
// Register MVC controller and API controller dependencies per request.
builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerDependency();
builder.RegisterType<DatabaseFactory>().As<IDatabaseFactory>().InstancePerLifetimeScope();
// Register service
builder.RegisterAssemblyTypes(typeof(ProfileService).Assembly)
.Where(t => t.Name.EndsWith("Service"))
.AsImplementedInterfaces().InstancePerDependency();
// Register repository
builder.RegisterAssemblyTypes(typeof(ProfileRepository).Assembly)
.Where(t => t.Name.EndsWith("Repository"))
.AsImplementedInterfaces().InstancePerDependency();
var container = builder.Build();
//for MVC Controller Set the dependency resolver implementation.
var resolverMvc = new AutofacDependencyResolver(container);
System.Web.Mvc.DependencyResolver.SetResolver(resolverMvc);
}
示例3: RegisterAutofac
public static void RegisterAutofac()
{
var builder = new ContainerBuilder();
// Register your MVC controllers.
builder.RegisterControllers(typeof(MvcApplication).Assembly);
// OPTIONAL: Register model binders that require DI.
builder.RegisterModelBinders(Assembly.GetExecutingAssembly());
builder.RegisterModelBinderProvider();
// OPTIONAL: Register web abstractions like HttpContextBase.
builder.RegisterModule<AutofacWebTypesModule>();
// OPTIONAL: Enable property injection in view pages.
builder.RegisterSource(new ViewRegistrationSource());
// OPTIONAL: Enable property injection into action filters.
builder.RegisterFilterProvider();
// Register services
RegisterServices(builder);
// Set the dependency resolver to be Autofac.
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
示例4: Application_Start
protected void Application_Start()
{
Database.SetInitializer(new TrainingDbInitializer());
var builder = new ContainerBuilder();
builder.RegisterType<EditableUserRepository>().As<IEditableRepository<User>>();
builder.RegisterType<EditableSysOpRepository>().As<IEditableRepository<SysOp>>();
builder.RegisterType<CompanyRepository>().As<IEditableRepository<Company>>();
builder.RegisterType<CommentRepository>().As<IEditableRepository<Comment>>();
builder.RegisterType<CourseRepository>().As<IEditableRepository<Course>>();
builder.RegisterType<EmployeeCourseRepository>().As<IEditableRepository<EmployeeCourse>>();
builder.RegisterType<DivisionRepository>().As<IEditableRepository<Division>>();
builder.RegisterType<EmployeeRepository>().As<IEditableRepository<Employee>>();
builder.RegisterType<EmployeeCourseStatusRepository>().As<IEditableRepository<EmployeeCourseStatus>>();
builder.RegisterType<InstructorRepository>().As<IEditableRepository<Instructor>>();
builder.RegisterType<RaceRepository>().As<IEditableRepository<Race>>();
builder.RegisterType<RegionRepository>().As<IEditableRepository<Region>>();
builder.RegisterType<ResultRepository>().As<IEditableRepository<Result>>();
builder.RegisterType<EmployeeDocumentRepository>().As<IEditableRepository<EmployeeDocument>>();
builder.RegisterType<TrainingScheduleRepository>().As<IEditableRepository<TrainingSchedule>>();
builder.RegisterType<EmployeeTrainingScheduleRepository>().As<IEditableRepository<EmployeeTrainingSchedule>>();
builder.RegisterType<TrainingManualRepository>().As<IEditableRepository<TrainingManual>>();
builder.RegisterType<CompanyBudgetRepository>().As<IEditableRepository<CompanyBudget>>();
builder.RegisterType<DivisionBudgetRepository>().As<IEditableRepository<DivisionBudget>>();
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
GlobalConfiguration.Configure(WebApiConfig.Register);
GlobalConfiguration.Configuration.MessageHandlers.Add(new BasicTrainingAuthMessageHandler());
}
示例5: ConfigureServices
// This method gets called by the runtime. Use this method to add services to the container.
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc();
// Create the Autofac container builder.
var builder = new ContainerBuilder();
// Add any Autofac modules or registrations.
builder.RegisterModule(new ServiceModule());
// Populate the services.
builder.Populate(services);
// Build the container.
var container = builder.Build();
// Resolve and return the service provider.
return container.Resolve<IServiceProvider>();
}
示例6: Configure
public static void Configure()
{
var builder = new ContainerBuilder();
var config = GlobalConfiguration.Configuration;
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
//builder.RegisterWebApiFilterProvider(config);
var dbPath = WebConfigurationManager.AppSettings["sqLiteDb"].Replace(@"~\", "");
bool useDiskConnOnlyValue;
if (!bool.TryParse(WebConfigurationManager.AppSettings["useDiskConnOnly"], out useDiskConnOnlyValue))
{
throw new InvalidOperationException("Invalid useDiskCOnnOnly in web.config");
}
var lucenceIndeDirectory = WebConfigurationManager.AppSettings["lucenceIndeDirectory"].Replace(@"~\", "");
builder.RegisterModule(new LuceneIndexModule(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, lucenceIndeDirectory)));
builder.RegisterModule(new ConnectionManagerModule(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, dbPath), useDiskConnOnlyValue));
builder.RegisterModule(new LocationControllerModule());
var container = builder.Build();
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
}
示例7: Application_Start
protected void Application_Start()
{
#region ApplicationStart
ContainerBuilder builder = new ContainerBuilder();
// Register your MVC controllers.
builder.RegisterControllers(typeof(MvcApplication).Assembly);
// Set the dependency resolver to be Autofac.
IContainer container = builder.Build();
BusConfiguration busConfiguration = new BusConfiguration();
busConfiguration.EndpointName("Samples.MvcInjection.WebApplication");
// ExistingLifetimeScope() ensures that IBus is added to the container as well,
// allowing you to resolve IBus from your own components.
busConfiguration.UseContainer<AutofacBuilder>(c => c.ExistingLifetimeScope(container));
busConfiguration.UseSerialization<JsonSerializer>();
busConfiguration.UsePersistence<InMemoryPersistence>();
busConfiguration.EnableInstallers();
bus = Bus.CreateSendOnly(busConfiguration);
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
#endregion
}
示例8: Bootstrapper
public Bootstrapper()
{
IContainer container = null;
var builder = new ContainerBuilder();
builder.RegisterModule(new AgathaClientModule
{
ContainerFactory = () => container,
RequestResponseAssembly = typeof (Nitrogen.Common.AssemblyHook).Assembly
});
builder.RegisterModule(new Log4NetModule {SectionName = "CommonLogging.Nitrogen.Client"});
builder.RegisterType<MessageStream>().As<IMessageStream>().SingleInstance();
builder.RegisterType<ShellViewModel>().AsSelf();
builder.RegisterModule(new WPFModule());
builder.RegisterType<WPFStartable>().AsSelf();
builder.RegisterType<ClientStartable>().AsSelf();
// DataExplorer
builder.RegisterModule(new DataExplorerModule());
builder.RegisterType<DataExplorerStartable>().AsSelf();
// Build the container
container = builder.Build();
// TODO : Ideally change this, so it isn't resolved like this
container.Resolve<WPFStartable>().Start();
container.Resolve<ClientStartable>().Start();
container.Resolve<DataExplorerStartable>().Start();
}
示例9: Init
public void Init() {
var builder = new ContainerBuilder();
// builder.RegisterModule(new ImplicitCollectionSupportModule());
builder.RegisterModule(new ContentModule());
builder.RegisterType<DefaultContentManager>().As<IContentManager>().SingleInstance();
builder.RegisterType<DefaultContentManagerSession>().As<IContentManagerSession>();
builder.RegisterType<AlphaHandler>().As<IContentHandler>();
builder.RegisterType<BetaHandler>().As<IContentHandler>();
builder.RegisterType<GammaHandler>().As<IContentHandler>();
builder.RegisterType<DeltaHandler>().As<IContentHandler>();
builder.RegisterType<EpsilonHandler>().As<IContentHandler>();
builder.RegisterType<FlavoredHandler>().As<IContentHandler>();
builder.RegisterType<StyledHandler>().As<IContentHandler>();
builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>));
_session = _sessionFactory.OpenSession();
builder.RegisterInstance(new DefaultContentManagerTests.TestSessionLocator(_session)).As<ISessionLocator>();
_session.Delete(string.Format("from {0}", typeof(GammaRecord).FullName));
_session.Delete(string.Format("from {0}", typeof(DeltaRecord).FullName));
_session.Delete(string.Format("from {0}", typeof(EpsilonRecord).FullName));
_session.Delete(string.Format("from {0}", typeof(ContentItemVersionRecord).FullName));
_session.Delete(string.Format("from {0}", typeof(ContentItemRecord).FullName));
_session.Delete(string.Format("from {0}", typeof(ContentTypeRecord).FullName));
_session.Flush();
_session.Clear();
_container = builder.Build();
_manager = _container.Resolve<IContentManager>();
}
示例10: configureIoC
private void configureIoC()
{
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.Register(ctx => LogManager.GetLogger("trace"))
.As<Logger>()
.InstancePerHttpRequest();
builder.RegisterType<ProcessRunner>()
.AsImplementedInterfaces()
.InstancePerDependency()
;
builder.RegisterType<DotProcessor>()
.AsImplementedInterfaces()
.SingleInstance()
;
builder.RegisterType<Ansi2HtmlConverter>()
.AsImplementedInterfaces()
.InstancePerDependency()
;
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
示例11: Setup
public static void Setup()
{
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterModelBinders(Assembly.GetExecutingAssembly());
builder.RegisterModelBinderProvider();
builder.RegisterModule<AutofacWebTypesModule>();
builder.RegisterSource(new ViewRegistrationSource());
builder.RegisterFilterProvider();
builder.RegisterType<PremiumCalculationService>().As<IPremiumCalculationService>();
builder.Register(context => new MapperConfiguration(configuration =>
{
configuration.AddProfile(new AutoMapperProfile());
}))
.AsSelf()
.SingleInstance();
builder.Register(context => context.Resolve<MapperConfiguration>()
.CreateMapper(context.Resolve))
.As<IMapper>()
.InstancePerLifetimeScope();
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
示例12: ConfigureDependencies
/// <summary>
/// Configures the multitenant dependency container.
/// </summary>
private static IContainer ConfigureDependencies()
{
// Register default dependencies in the application container.
var builder = new ContainerBuilder();
builder.RegisterType<Consumer>().As<IDependencyConsumer>().InstancePerDependency();
builder.RegisterType<BaseDependency>().As<IDependency>().SingleInstance();
var appContainer = builder.Build();
// Create the multitenant container.
var mtc = new MultitenantContainer(_tenantIdentifier, appContainer);
// Configure overrides for tenant 1. Tenant 1 registers their dependencies
// as instance-per-dependency.
mtc.ConfigureTenant('1', b => b.RegisterType<Tenant1Dependency>().As<IDependency>().InstancePerDependency());
// Configure overrides for tenant 2. Tenant 2 registers their dependencies
// as singletons.
mtc.ConfigureTenant('2', b => b.RegisterType<Tenant2Dependency>().As<IDependency>().SingleInstance());
// Configure overrides for the default tenant. That means the default
// tenant will have some different dependencies than other unconfigured
// tenants.
mtc.ConfigureTenant(null, b => b.RegisterType<DefaultTenantDependency>().As<IDependency>().SingleInstance());
return mtc;
}
示例13: Configure
/// <summary>
/// Configuration routine of the autofac container.
/// </summary>
/// <param name="eventBus">The event bus.</param>
/// <param name="hoardeManager">The hoarde manager.</param>
/// <param name="configurationManager">The host's configuration manager.</param>
public static void Configure(IEventBus eventBus, ServiceModel.IHoardeManager hoardeManager, INutConfiguration configurationManager)
{
var builder = new ContainerBuilder();
builder.RegisterInstance(eventBus);
builder.RegisterInstance(hoardeManager);
builder.RegisterInstance(configurationManager);
builder.RegisterType<ServiceModel.ServicesManager>().AsImplementedInterfaces().SingleInstance();
builder.RegisterType<ServiceModel.PollingClientCollection>().AsSelf().SingleInstance();
builder.RegisterType<ServiceModel.RegisteredPackagesPollingClient>().AsSelf().SingleInstance();
builder.RegisterType<ServiceModel.ReleasesPollingClient>();
builder.RegisterType<ConfigurationManagement.DbConfigurationSettings>();
// we will apply most of the configuration in one or more assembly modules.
builder.RegisterAssemblyModules(typeof(AutofacConfig).Assembly);
switch (configurationManager.Mode)
{
case ExecutionMode.Development:
builder.RegisterType<Repositories.OnDisk.OnDiskPackageRepository>().AsImplementedInterfaces().InstancePerLifetimeScope();
break;
case ExecutionMode.Production:
builder.RegisterType<Repositories.SQLiteRepositories.PackageRepository>().AsImplementedInterfaces().InstancePerLifetimeScope();
break;
default:
builder.RegisterType<Repositories.SQLiteRepositories.PackageRepository>().AsImplementedInterfaces().InstancePerLifetimeScope();
_log.WarnFormat("Unknown execution mode '{mode}'. Registered Sqlite Repository.", configurationManager.Mode);
break;
}
_container = builder.Build();
}
示例14: Init
public void Init()
{
_users = new List<UserEntity>();
for (var ndx = 0; ndx < 10; ++ndx)
{
var postfix = ndx.ToString();
var user = new UserEntity
{
UserEntityId = ndx + 1,
DateRegistered = ServerTime.Now,
UserName = "User" + postfix,
Email = String.Format("user.{0}@test.com", ndx)
};
_users.Add(user);
}
Mapper.CreateMap<UserEntity, User>()
.ForMember(p => p.Id, opt => opt.MapFrom(src => src.UserEntityId))
.IgnoreAllNonExisting();
var builder = new ContainerBuilder();
builder.RegisterType<QueryBuilder>().As<IQueryBuilder>();
var entitiesRepo = new Repository<UserEntity>(_users);
var usersRepo = new Repository<User>(_users.Select(p
=> p.MapTo<User>()));
builder.RegisterInstance(entitiesRepo).As<IRepository<UserEntity>>().SingleInstance();
builder.RegisterInstance(usersRepo).As<IRepository<User>>().SingleInstance();
var container = builder.Build();
var resolver = new AutofacDependencyResolver(container);
DependencyResolver.SetResolver(resolver);
}
示例15: RegisterTypes
public static void RegisterTypes()
{
var builder = new ContainerBuilder();
builder.RegisterType<VideoRepository>().As<IVideoRepository>().InstancePerLifetimeScope();
builder.RegisterType<OrderRepository>().As<IOrderRepository>().InstancePerLifetimeScope();
builder.RegisterType<UserRepository>().As<IUserRepository>();
builder.RegisterType<MockPaymentProcessor>().As<IPaymentProcessor>().InstancePerLifetimeScope();
builder.RegisterType<StoreController>()
.UsingConstructor(typeof(IVideoRepository), typeof(IUserRepository));
builder.RegisterType<CartController>()
.UsingConstructor(typeof(IVideoRepository));
builder.RegisterType<WishlistController>()
.UsingConstructor(typeof(IUserRepository), typeof(IVideoRepository));
builder.RegisterType<OrderController>()
.UsingConstructor(typeof(IVideoRepository), typeof(IOrderRepository), typeof(IUserRepository), typeof(IPaymentProcessor));
builder.RegisterType<HomeController>()
.UsingConstructor(typeof(IVideoRepository), typeof(IOrderRepository), typeof(IUserRepository));
builder.RegisterType<VideosController>()
.UsingConstructor(typeof(IVideoRepository));
builder.RegisterType<OrdersController>()
.UsingConstructor(typeof(IOrderRepository));
builder.RegisterType<UsersController>()
.UsingConstructor(typeof(IUserRepository));
builder.RegisterType<AccountController>()
.UsingConstructor(typeof(IUserRepository));
var container = builder.Build();
var resolver = new AutofacDependencyResolver(container);
DependencyResolver.SetResolver(resolver);
}