本文整理汇总了C#中Autofac.ContainerBuilder.RegisterInstance方法的典型用法代码示例。如果您正苦于以下问题:C# ContainerBuilder.RegisterInstance方法的具体用法?C# ContainerBuilder.RegisterInstance怎么用?C# ContainerBuilder.RegisterInstance使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Autofac.ContainerBuilder
的用法示例。
在下文中一共展示了ContainerBuilder.RegisterInstance方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Load
protected override void Load(ContainerBuilder builder)
{
#if MOBILE
builder.RegisterType<UiContext>().AsImplementedInterfaces();
builder.RegisterInstance(new MobileService(new UiContext())).AsImplementedInterfaces();
builder.RegisterType<VmPageMappings>().AsImplementedInterfaces();
#else
builder.RegisterInstance(new MobileService()).AsImplementedInterfaces();
#endif
builder.RegisterType<MessageBox>().AsImplementedInterfaces();
builder.RegisterType<AzureStorageService>().AsImplementedInterfaces();
builder.RegisterType<AppSettings>().AsImplementedInterfaces();
builder.RegisterType<Logger>().AsImplementedInterfaces();
builder.RegisterType<PhotoChooser>().AsImplementedInterfaces();
builder.RegisterType<MvxJsonConverter>().AsImplementedInterfaces();
#if NETFX_CORE
builder.RegisterType<ShareManager>().AsImplementedInterfaces();
builder.RegisterType<SecondaryPinner>().AsImplementedInterfaces();
builder.RegisterAssemblyTypes(typeof(ViewModelBase).GetTypeInfo().Assembly)
.Where(t => t.GetTypeInfo().IsSubclassOf(typeof(ViewModelBase)));
builder.RegisterAssemblyTypes(typeof(PollImageViewModelBase).GetTypeInfo().Assembly)
.Where(t => t.GetTypeInfo().IsSubclassOf(typeof(PollImageViewModelBase)));
#else
builder.RegisterType<UiContext>().AsImplementedInterfaces();
builder.RegisterAssemblyTypes(typeof(ViewModelBase).Assembly)
.Where(t => t.IsSubclassOf(typeof(ViewModelBase)));
builder.RegisterAssemblyTypes(typeof(PollImageViewModelBase).Assembly)
.Where(t => t.IsSubclassOf(typeof(PollImageViewModelBase)));
#endif
}
示例2: 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();
}
示例3: Init
public void Init(IEnumerable<Type> dataMigrations) {
var builder = new ContainerBuilder();
_folders = new StubFolders();
var contentDefinitionManager = new Mock<IContentDefinitionManager>().Object;
builder.RegisterInstance(new ShellSettings { DataTablePrefix = "TEST_"});
builder.RegisterType<SqlServerDataServicesProvider>().As<IDataServicesProvider>();
builder.RegisterType<DataServicesProviderFactory>().As<IDataServicesProviderFactory>();
builder.RegisterType<NullInterpreter>().As<IDataMigrationInterpreter>();
builder.RegisterInstance(_folders).As<IExtensionFolders>();
builder.RegisterInstance(contentDefinitionManager).As<IContentDefinitionManager>();
builder.RegisterType<ExtensionManager>().As<IExtensionManager>();
builder.RegisterType<DataMigrationManager>().As<IDataMigrationManager>();
builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>));
builder.RegisterType<StubCacheManager>().As<ICacheManager>();
builder.RegisterType<StubParallelCacheContext>().As<IParallelCacheContext>();
builder.RegisterType<StubAsyncTokenProvider>().As<IAsyncTokenProvider>();
_session = _sessionFactory.OpenSession();
builder.RegisterInstance(new DefaultContentManagerTests.TestSessionLocator(_session)).As<ISessionLocator>().As<ITransactionManager>();
foreach(var type in dataMigrations) {
builder.RegisterType(type).As<IDataMigration>();
}
_container = builder.Build();
_container.Resolve<IExtensionManager>();
_dataMigrationManager = _container.Resolve<IDataMigrationManager>();
_repository = _container.Resolve<IRepository<DataMigrationRecord>>();
_transactionManager = _container.Resolve<ITransactionManager>();
InitDb();
}
示例4: Setup
public void Setup() {
_databaseFileName = Path.GetTempFileName();
_sessionFactory = DataUtility.CreateSessionFactory(_databaseFileName);
_tempFolder = Path.GetTempFileName();
File.Delete(_tempFolder);
var appDataFolder = AppDataFolderTests.CreateAppDataFolder(_tempFolder);
var builder = new ContainerBuilder();
_session = _sessionFactory.OpenSession();
builder.RegisterInstance(appDataFolder).As<IAppDataFolder>();
builder.RegisterType<SqlCeDataServicesProvider>().As<IDataServicesProvider>();
builder.RegisterType<DataServicesProviderFactory>().As<IDataServicesProviderFactory>();
builder.RegisterType<StubReportsCoordinator>().As<IReportsCoordinator>();
builder.RegisterType<DefaultDataMigrationInterpreter>().As<IDataMigrationInterpreter>();
builder.RegisterType<SqlCeCommandInterpreter>().As<ICommandInterpreter>();
builder.RegisterType<SessionConfigurationCache>().As<ISessionConfigurationCache>();
builder.RegisterType<SessionFactoryHolder>().As<ISessionFactoryHolder>();
builder.RegisterType<DefaultDatabaseCacheConfiguration>().As<IDatabaseCacheConfiguration>();
builder.RegisterType<StubHostEnvironment>().As<IHostEnvironment>();
builder.RegisterInstance(new TestTransactionManager(_session)).As<ITransactionManager>();
builder.RegisterInstance(new ShellBlueprint { Records = Enumerable.Empty<RecordBlueprint>() }).As<ShellBlueprint>();
builder.RegisterInstance(new ShellSettings { Name = "temp", DataProvider = "SqlCe", DataTablePrefix = "TEST" }).As<ShellSettings>();
builder.RegisterModule(new DataModule());
_container = builder.Build();
_interpreter = _container.Resolve<IDataMigrationInterpreter>() as DefaultDataMigrationInterpreter;
_schemaBuilder = new SchemaBuilder(_interpreter);
}
示例5: 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);
}
示例6: Init
public void Init()
{
var builder = new ContainerBuilder();
builder.RegisterType<NServiceBusCommitDispatcher>()
.As<NServiceBusCommitDispatcher>()
.AsImplementedInterfaces()
.SingleInstance();
builder.RegisterType<SagaEventStoreRepository>().AsImplementedInterfaces();
builder.RegisterType<EventStoreRepository>().AsImplementedInterfaces();
builder.RegisterType<AggregateFactory>().AsImplementedInterfaces();
builder.RegisterType<ConflictDetector>().AsImplementedInterfaces();
var documentStore = BuildRavenDocumentStore();
var eventStore = InitializeEventSourcing();
builder.RegisterInstance(documentStore);
builder.RegisterInstance(eventStore);
Container = builder.Build();
NServiceBus
.SetLoggingLibrary.Log4Net(log4net.Config.XmlConfigurator.Configure);
NServiceBus
.Configure.With().AutofacBuilder(Container)
.MsmqSubscriptionStorage()
.XmlSerializer();
}
示例7: Configure
public static IContainer Configure(WsFederationPluginOptions options, InternalConfiguration internalConfig)
{
if (internalConfig == null) throw new ArgumentNullException("internalConfig");
if (options == null) throw new ArgumentNullException("options");
var factory = options.Factory;
factory.Validate();
var builder = new ContainerBuilder();
// mandatory from factory
builder.Register(factory.CoreSettings);
builder.Register(factory.UserService);
builder.Register(factory.RelyingPartyService);
builder.Register(factory.WsFederationSettings);
// validators
builder.RegisterType<SignInValidator>().AsSelf();
// processors
builder.RegisterType<SignInResponseGenerator>().AsSelf();
builder.RegisterType<MetadataResponseGenerator>().AsSelf();
// general services
builder.RegisterType<CookieMiddlewareTrackingCookieService>().As<ITrackingCookieService>();
builder.RegisterInstance(options).AsSelf();
builder.RegisterInstance(internalConfig).AsSelf();
// load core controller
builder.RegisterApiControllers(typeof(WsFederationController).Assembly);
return builder.Build();
}
示例8: SetupDependencies
private static void SetupDependencies()
{
IContainer container = null;
var containerBuilder = new ContainerBuilder();
//containerBuilder.RegisterModule<ApplicationServicesModule>();
//containerBuilder.RegisterType<NsbEventBus>().As<IEventBus>();
containerBuilder.RegisterType<RavenDBEventStore>().As<IEventStore>();
containerBuilder.RegisterInstance<ICommandService>(InitializeCommandService());
containerBuilder.RegisterInstance<IEventBus>(InitializeEventBus());
//InitializeNServiceBus(container);
containerBuilder.Register(x => container);
// var config = new AutofacConfiguration(x =>
// {
// var eventBus = InitializeEventBus();
// var eventStore = InitializeEventStore();
// x.For{IEventBus}().Use(eventBus);
// x.For{IEventStore}().Use(eventStore);
// x.For{IUnitOfWorkFactory}().Use{UnitOfWorkFactory}();
// }
//);
container = containerBuilder.Build();
AutofacConfiguration config = new AutofacConfiguration(container);
// I believe this is a single call to configure inject all component dependencies
// e.g. NcqrsEnvironment.SetDefault<IEventBus>( InitializeEventBus() );
NcqrsEnvironment.Configure(config);
}
示例9: Initialize
public static IContainer Initialize() {
Logger.Info(typeof (ContainerConfig), "Initializing container...");
ContainerBuilder builder = new ContainerBuilder();
ConfigFileConfigurationProvider configurationProvider = new ConfigFileConfigurationProvider();
builder.RegisterInstance(configurationProvider.Service).As<IServiceConfiguration>();
builder.RegisterInstance(configurationProvider.Repository).As<IApplicationRepositoryConfiguration>();
builder.RegisterInstance(configurationProvider.Authentication).As<IAuthenticationConfiguration>();
builder.RegisterType<FileSystemApplicationRepository>().As<IApplicationRepository>();
builder.RegisterType<SystemDateTimeFactory>().As<IDateTimeFactory>();
// register API controllers
builder.RegisterApiControllers(typeof (PackagesApiController).Assembly);
builder.RegisterControllers(typeof (HomeController).Assembly);
// build container
Container = Dependency.Build(builder);
GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(Container);
DependencyResolver.SetResolver(new AutofacDependencyResolver(Container));
Logger.Info(typeof (ContainerConfig), "Container initialized");
return (Container);
}
示例10: Load
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<AutofacDependencyResolver>().As<IDependencyResolver>().SingleInstance();
builder.RegisterInstance(GlobalFilters.Filters).As<GlobalFilterCollection>().SingleInstance();
builder.RegisterInstance(RouteTable.Routes).As<RouteCollection>().SingleInstance();
builder.RegisterFilterProvider();
}
示例11: Load
protected override void Load(ContainerBuilder builder)
{
#region mock IPostRepository
Mock<IPostRepository> mockPost = new Mock<IPostRepository>();
var posts = new List<Post>()
{
new Post() {Id = 1, Title = "first blog", Published = DateTime.Now.AddDays(-1)},
new Post() {Id = 2, Title = "second blog", Published = DateTime.Now.AddDays(-2)},
new Post() {Id = 3, Title = "third blog", Published = DateTime.Now.AddDays(-3)},
};
mockPost.Setup(m => m.GetAll()).Returns(posts.AsQueryable());
mockPost.Setup(m => m.Get(It.IsAny<int>())).Returns(posts.SingleOrDefault(p => p.Id == 1));
builder.RegisterInstance(mockPost.Object).As<IPostRepository>().SingleInstance();
#endregion
#region mock IUserRepository
Mock<IUserRepository> mockUser = new Mock<IUserRepository>();
var users = new List<User>
{
new User()
{Id = 1, Name = "sa", Email = "[email protected]", Username = "sa", Password = "sa"},
//new User()
// {
// Id = 2,
// Name = "admin",
// Email = "[email protected]",
// Username = "admin",
// Password = "admin"
// }
};
mockUser.Setup(m => m.GetAll()).Returns(users.AsQueryable());
builder.RegisterInstance(mockUser.Object).As<IUserRepository>().SingleInstance();
#endregion
}
示例12: ApplicationStarted
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
var builder = new ContainerBuilder();
//register umbracocontext as a factory
builder.Register(c => UmbracoContext.Current).AsSelf();
//add all the controllers from the assembly
builder.RegisterControllers(System.Reflection.Assembly.GetExecutingAssembly());
//getting null pointer exception in the backend of umbraco if I don't load this one
builder.RegisterApiControllers(typeof(Umbraco.Web.Trees.ApplicationTreeController).Assembly);
//add custom class to the container as transient instance
builder.RegisterType<FriendService>().As<IFriendService>();
//se if we can just pass the instances to the builder, works and not needed cause of the umbracocontext, but gives us more control
builder.RegisterInstance(UmbracoContext.Current.Application.Services.ContentService);
builder.RegisterInstance(UmbracoContext.Current.Application.Services.MemberService);
builder.RegisterInstance(UmbracoContext.Current.Application.Services.RelationService);
builder.RegisterInstance(UmbracoContext.Current.Application.Services.MediaService);
builder.RegisterInstance(UmbracoContext.Current.Application.DatabaseContext.Database).As<Umbraco.Core.Persistence.Database>();
//register the myhelper class should be a interface etc.
builder.RegisterType<MyHelper>().As<IMyHelper>();
var container = builder.Build();
//setup the webapi dependency resolver to use autofac
System.Web.Mvc.DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
base.ApplicationStarted(umbracoApplication, applicationContext);
}
示例13: RegisterComponents
public override void RegisterComponents(ContainerBuilder builder)
{
base.RegisterComponents(builder);
builder.RegisterInstance(this).As<NuGetApiService>();
var config = ConfigureWebApi();
builder.RegisterInstance(config).AsSelf();
builder
.RegisterApiControllers(GetControllerAssemblies().ToArray())
.OnActivated(e =>
{
var nugetController = e.Instance as NuGetApiController;
if (nugetController != null)
{
nugetController.Host = Host;
nugetController.Service = this;
nugetController.Container = Container;
}
})
.InstancePerApiRequest();
builder.RegisterWebApiFilterProvider(config);
builder.RegisterWebApiModelBinderProvider();
}
示例14: WithParameter_Integration
public void WithParameter_Integration()
{
var builder = new ContainerBuilder();
builder.RegisterInstance<string>("example_value_one")
.Keyed<string>("key_one")
.SingleInstance();
builder.RegisterInstance<string>("example_value_two")
.Keyed<string>("key_two")
.SingleInstance();
builder.RegisterType<ExampleType>()
.WithParameter("value1", c => c.ResolveKeyed<string>("key_one"))
.WithParameter("value2", c => c.ResolveKeyed<string>("key_two"))
.SingleInstance();
using (var container = builder.Build())
{
var example = container.ResolveOptional<ExampleType>();
Assert.That(example, Is.Not.Null);
Assert.That(example.Value1, Is.EqualTo("example_value_one"));
Assert.That(example.Value2, Is.EqualTo("example_value_two"));
}
}
示例15: CreateShell
internal Shell CreateShell(BrowseForRepositoryEvent browseForRepositoryEvent, Arguments arguments)
{
var builder = new Autofac.ContainerBuilder();
ChorusUIComponentsInjector.Inject(builder, _projectPath, SyncUIFeatures.Advanced);
builder.RegisterInstance(browseForRepositoryEvent).As<BrowseForRepositoryEvent>().SingleInstance();
//For now, we like the idea of just using the login name. But
//this allows someone to override that in the ini (which would be for all users of this machine, then)
builder.Register<IChorusUser>(c => new ChorusUser(c.Resolve<HgRepository>().GetUserNameFromIni(new NullProgress(), System.Environment.UserName)));
builder.RegisterType<Shell>();
if(arguments!=null)
{
builder.RegisterInstance(arguments);
Synchronizer.s_testingDoNotPush = arguments.DontPush; //hack, at this point it would take a lot of plumbing
//to get this properly to any synchronizer that is created. Can be fixed if/when we go to the
//autofac generated factor approach
}
_container = builder.Build();
var shell= _container.Resolve<Shell>();
var system = new ChorusSystem(_projectPath);
system.Init(string.Empty);
shell.AddPage("Review", system.WinForms.CreateHistoryPage());
shell.AddPage("Notes", system.WinForms.CreateNotesBrowser());
shell.AddPage("Send/Receive", _container.Resolve<SyncPanel>());
shell.AddPage("Settings", _container.Resolve<SettingsView>());
shell.AddPage("Troubleshooting", _container.Resolve<TroubleshootingView>());
return shell;
}