本文整理汇总了C#中WindsorContainer类的典型用法代码示例。如果您正苦于以下问题:C# WindsorContainer类的具体用法?C# WindsorContainer怎么用?C# WindsorContainer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
WindsorContainer类属于命名空间,在下文中一共展示了WindsorContainer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Castle
/// <summary>配置默认的Castle容器
/// <remarks>默认使用XmlInterpreter初始化</remarks>
/// </summary>
/// <param name="configuration"></param>
/// <param name="func">执行额外的配置</param>
/// <returns></returns>
public static Configuration Castle(this Configuration configuration, Action<WindsorResolver> func)
{
var container = new WindsorContainer();
//从配置文件初始化
container.Install(new ConfigurationInstaller(new XmlInterpreter()));
var resolver = new WindsorResolver(container);
//设置解释器实例
configuration.Resolver(resolver);
//强制注册Log4Net日志工厂+增加注入运行时变量 20111130
resolver.Container.Log4NetLoggerFactory(
() => configuration.RuntimeProperties(Configuration.RuntimeProperties_Environment)
, () => configuration.RuntimeProperties(Configuration.RuntimeProperties_Environment_Error));
//强制设置Common.Logging使用Log4Net实现且使用外部配置的log4net实例 EXTERNAL
Common.Logging.LogManager.Adapter = new Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter(new NameValueCollection() { { "configType", "EXTERNAL" } });
//记录启动信息
var log = DependencyResolver
.Resolve<ILoggerFactory>()
.Create(typeof(ConfigurationExtensions));
log.Info("不启用NamingSubSystem=NamingSubsystemForDefaultComponent,Castle升级至3.0后无需此子系统");
log.Info("强制使用Log4Net日志工厂");
log.Info("强制设置Common.Logging使用Common.Logging.Log4Net实现");
log.Debug("来自Configuration的在日志组件未初始化前的调试信息:\n" + configuration.PopMessages());
//额外的容器配置
func(resolver);
return configuration;
}
示例2: TestBasicOperations
public void TestBasicOperations()
{
WindsorContainer container = new WindsorContainer(new DefaultConfigurationStore());
container.AddFacility("transactionmanagement", new TransactionFacility());
container.AddComponent("transactionmanager",
typeof(ITransactionManager), typeof(MockTransactionManager));
container.AddComponent("services.customer", typeof(CustomerService));
CustomerService service = (CustomerService)container["services.customer"];
service.Insert("TestCustomer", "Rua P Leite, 33");
MockTransactionManager transactionManager = (MockTransactionManager)
container["transactionmanager"];
Assert.AreEqual(1, transactionManager.TransactionCount);
Assert.AreEqual(1, transactionManager.CommittedCount);
Assert.AreEqual(0, transactionManager.RolledBackCount);
try
{
service.Delete(1);
}
catch (Exception)
{
// Expected
}
Assert.AreEqual(2, transactionManager.TransactionCount);
Assert.AreEqual(1, transactionManager.CommittedCount);
Assert.AreEqual(1, transactionManager.RolledBackCount);
}
示例3: ConfigureIoC
static IWindsorContainer ConfigureIoC()
{
var container = new WindsorContainer();
container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel, true));
container.Install(Configuration.FromAppConfig(), FromAssembly.This(), FromAssembly.Containing<GuestBookXmlProvider>());
return container;
}
示例4: StartableComponentShouldNotStartIfExceptionThrownByInstaller
public void StartableComponentShouldNotStartIfExceptionThrownByInstaller()
{
UsesIEmptyService.instancesCreated = 0;
using (var container = new WindsorContainer())
{
container.AddFacility<StartableFacility>(f => f.DeferredStart());
Assert.Throws<NotImplementedException>(
() =>
container.Install(new ActionBasedInstaller(c => c.Register(Component.For<UsesIEmptyService>().Start())),
new ActionBasedInstaller(c => c.Register(Component.For<IEmptyService>().ImplementedBy<EmptyServiceA>())),
new ActionBasedInstaller(c => { throw new NotImplementedException(); })));
// In this scenario, I've registered IDependencyOfStartableComponent
// before the ExceptionThrowingInstaller gets a chance to gum up the works
// I would expect that the "deferred start" code NOT run here,
// and the StartableComponent remain un-instantiated.
// However, Castle is creating the StartableComponent anyway
// and then allows the NotImplementedException to bubble out.
// Presumably, this is due to the "deferred start" mechanism
// being implemented by a using() block or something similar
// via OptimizeDependencyResolutionDisposable.Dispose()
Assert.AreEqual(0, UsesIEmptyService.instancesCreated);
}
}
示例5: Main
// Models singleton over transient instance models
static void Main(string[] args)
{
IWindsorContainer container =
new WindsorContainer(new XmlInterpreter("windsor.config"));
//IWindsorContainer container = CreateContainer();
IBar bar = container.Resolve<IBar>();
if (bar != null)
{
bar.DisplayTime();
}
container.Release(bar);
// Mimic a time delay.
System.Threading.Thread.Sleep(2000);
IBar bar2 = container.Resolve<IBar>();
if (bar2 != null)
{
bar2.DisplayTime();
}
container.Release(bar2);
Console.Write("Press <ENTER> to exit...");
Console.ReadLine();
}
示例6: Register
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver();
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}"
);
IWindsorContainer container = new WindsorContainer();
container.Register(
Classes
.FromThisAssembly()
.BasedOn<ApiController>()
.LifestyleScoped()
);
container.Register(
Component.For<IBetDataAccess>().ImplementedBy<BetDataAccess>(),
Component.For<IBetRiskCalculator>().ImplementedBy<BetRiskCalculator>(),
Component.For<ICustomerRiskCalculator>().ImplementedBy<CustomerRiskCalculator>(),
Component.For<IRiskService>().ImplementedBy<RiskService>()
);
config.DependencyResolver = new WindsorDependencyResolver(container.Kernel);
}
示例7: UseCastleWindsor
/// <summary>
/// Configure castle windsor as the container creating a new container.
/// </summary>
/// <param name="configuration"></param>
/// <returns></returns>
public static Configuration UseCastleWindsor(this Configuration configuration)
{
ParameterCheck.ParameterRequired(configuration, "configuration");
var container = new WindsorContainer();
return UseCastleWindsor(configuration, container);
}
示例8: SetUp
public void SetUp()
{
var compositeDatabaseConnection =
MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("test-db"));
Container = new WindsorContainer();
setAzureCredentials(Container);
Fabric = new ConsoleFabric(Container);
var composite = new BasicCompositeApp(Container)
{
Name = "Euclid.TestingSupport.HostingFabricFixture.Composite",
Description = "A composite used in specification tests"
};
composite.RegisterNh(compositeDatabaseConnection, false);
foreach (var agentAssembly in _agentAssemblies)
{
composite.AddAgent(agentAssembly);
}
composite.Configure(getCompositeSettings());
Fabric.Initialize(getFabricSettings());
Fabric.InstallComposite(composite);
composite.CreateSchema(compositeDatabaseConnection, true);
Fabric.Start();
}
示例9: AddCoreFromXML
public void AddCoreFromXML()
{
var container = new WindsorContainer(new XmlInterpreter(new StaticContentResource(@"<castle>
<facilities>
<facility id='solr' type='Castle.Facilities.SolrNetIntegration.SolrNetFacility, Castle.Facilities.SolrNetIntegration'>
<solrURL>http://localhost:8983/solr/defaultCore</solrURL>
<cores>
<core id='core0-id'>
<documentType>Castle.Facilities.SolrNetIntegration.Tests.Tests+Document, Castle.Facilities.SolrNetIntegration.Tests</documentType>
<url>http://localhost:8983/solr/core0</url>
</core>
<core id='core1-id'>
<documentType>Castle.Facilities.SolrNetIntegration.Tests.Tests+Document, Castle.Facilities.SolrNetIntegration.Tests</documentType>
<url>http://localhost:8983/solr/core1</url>
</core>
<core id='core2-id'>
<documentType>Castle.Facilities.SolrNetIntegration.Tests.Tests+Core1Entity, Castle.Facilities.SolrNetIntegration.Tests</documentType>
<url>http://localhost:8983/solr/core1</url>
</core>
</cores>
</facility>
</facilities>
</castle>")));
TestCores(container);
}
示例10: CanRegisterSimpleService
public void CanRegisterSimpleService()
{
var c = new WindsorContainer();
c.Register(Component.For<IDependency>().ImplementedBy<DependencyA>());
Assert.That(c.Resolve<IDependency>(), Is.InstanceOf<DependencyA>());
}
开发者ID:DrivenSoftware,项目名称:Driven.WindsorContainerRegistrationSamples,代码行数:7,代码来源:SingleRegistration.cs
示例11: Execute
public void Execute()
{
var container = new WindsorContainer();
//container.Kernel.ComponentModelBuilder.RemoveContributor(
// container.Kernel.ComponentModelBuilder.Contributors.OfType<PropertiesDependenciesModelInspector>().Single());
//container.Kernel.ReleasePolicy = new NoTrackingReleasePolicy();
//container.AddFacility<EventAggregatorFacility>();
container.Register
(
Component.For<IWindsorContainer>().Instance(container),
Component.For<IViewManager>().ImplementedBy<ViewManager>().LifestyleSingleton(),
Component.For<IRMSController>().ImplementedBy<RMSController>().LifestyleSingleton(),
Component.For<IEventPublisher>().ImplementedBy<EventPublisher>().LifestyleBoundTo<IService>(),
Classes.FromThisAssembly().BasedOn<IView>().WithService.FromInterface().LifestyleTransient(),
Classes.FromAssemblyNamed("BTE.RMS.Presentation.Logic.WPF")
.BasedOn<WorkspaceViewModel>()
.LifestyleTransient(),
Classes.FromAssemblyNamed("BTE.RMS.Presentation.Logic.WPF")
.BasedOn<IService>()
.WithService.FromInterface()
.LifestyleSingleton(),
Classes.FromAssemblyNamed("BTE.RMS.Presentation.Persistence.WPF")
.BasedOn<IRepository>()
.WithService.FromInterface()
.LifestyleBoundToNearest<IService>()
);
var locator = new WindsorServiceLocator(container);
ServiceLocator.SetLocatorProvider(() => locator);
RMSClientConfig.BaseApiSiteAddress = "http://localhost:9461/";
}
示例12: Main
public static void Main(string[] args)
{
var container = new WindsorContainer();
container.Register (
Component.For<ManagerService>()
.LifeStyle.Singleton);
container.Register (
Component.For<UnmanagedService>()
.Interceptors<ManagerService>());
var managerService = container.Resolve<ManagerService>();
managerService.Start ();
var unmanagedSvc = container.Resolve<UnmanagedService>();
unmanagedSvc.Start ();
Console.WriteLine ("Press enter to stop the service");
Console.ReadLine ();
managerService.Stop ();
unmanagedSvc.Stop ();
container.Dispose ();
}
示例13: InstallAssemblies
/// <summary>
/// Installs the assemblies.
/// </summary>
/// <param name = "container">The container.</param>
/// <param name = "assemblies">The assemblies.</param>
public static void InstallAssemblies(this IIoCContainer container, Assembly[] assemblies)
{
//Contract.Requires(container != null);
//Contract.Requires(assemblies != null);
using (var registrationContainer = new WindsorContainer())
{
foreach (var assembly in assemblies)
{
try
{
//container.Install(FromAssembly.Instance(assembly));
registrationContainer.Register(AllTypes.FromAssembly(assembly)
.IncludeNonPublicTypes()
.BasedOnAsService<IComponentInstaller>()
.Configure(c => c.LifeStyle.Transient));
}
catch (Exception e)
{
var msg = String.Format("Could not load assembly '{0}' because related assembly can't be loaded. Exception details: {1}", assembly.FullName, e.Message);
_logger.Fatal(msg, e);
throw new Exception(msg);
}
}
foreach (var item in registrationContainer.ResolveAll<IComponentInstaller>())
item.Install(container, assemblies);
}
}
示例14: App
public App()
{
try
{
InitializeComponent();
var logger = new ApplicationLogger();
Logger.Register(logger);
this.InstallExceptionHandler(new TestExceptionHandler(this, logger, false));
ThreadingFactory.Set(new ApplicationTaskScheduler(logger));
var container = new WindsorContainer();
var configuration = new Configuration.Configuration(container);
configuration.Install();
DialogService.ShowMain(new MainViewModel(configuration.BaseApiUrl));
}
catch (Exception exception)
{
Logger.Error(exception);
}
}
示例15: Main
static void Main(string[] args)
{
var container = new WindsorContainer(new XmlInterpreter()).Install(FromAssembly.This());
container.Kernel.Resolver.AddSubResolver(new ArrayResolver(container.Kernel));
HostFactory.Run(r =>
{
r.Service<IScheduleLimIntegration>(s =>
{
s.ConstructUsing(name => new ScheduleWorker(container));
s.WhenStarted(tc => tc.Start());
s.WhenStopped(tc =>
{
tc.End();
container.Release(tc);
container.Dispose();
});
});
r.RunAsLocalSystem();
r.SetDescription(System.Configuration.ConfigurationManager.AppSettings["service/config/description"]);
r.SetDisplayName(System.Configuration.ConfigurationManager.AppSettings["service/config/displayName"]);
r.SetServiceName(System.Configuration.ConfigurationManager.AppSettings["service/config/name"]);
});
}