本文整理汇总了C#中IServiceProvider.TryGetService方法的典型用法代码示例。如果您正苦于以下问题:C# IServiceProvider.TryGetService方法的具体用法?C# IServiceProvider.TryGetService怎么用?C# IServiceProvider.TryGetService使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IServiceProvider
的用法示例。
在下文中一共展示了IServiceProvider.TryGetService方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CreateTempGenerateCodeCommand
public static GenerateProductCodeCommand CreateTempGenerateCodeCommand(this IProductElement element,
IServiceProvider sp
, string targetFileName
, string targetPath
, string templateUri
, string namePrefix = "GenerateCode"
, string buildAction = "Compile")
{
var guid = Guid.NewGuid();
ISolution solution = sp.TryGetService<ISolution>();
IPatternManager patternManager = sp.TryGetService<IPatternManager>();
IUriReferenceService uriService = sp.TryGetService<IUriReferenceService>();
var command = new GenerateProductCodeCommand
{
TargetBuildAction = buildAction,
TargetCopyToOutput = CopyToOutput.DoNotCopy,
Settings = new EmptySettings { Name = String.Format("{0}{1}", namePrefix, guid.ToString()), Id = guid },
PatternManager = patternManager,
UriService = uriService,
Solution = solution,
ServiceProvider = sp,
TargetFileName = targetFileName,
TargetPath = targetPath,
CurrentElement = element,
TemplateUri = new Uri(templateUri)
};
return command;
}
示例2: Initialize
public virtual DbContextConfiguration Initialize(
[NotNull] IServiceProvider externalProvider,
[NotNull] IServiceProvider scopedProvider,
[NotNull] DbContextOptions contextOptions,
[NotNull] DbContext context,
ServiceProviderSource serviceProviderSource)
{
Check.NotNull(externalProvider, "externalProvider");
Check.NotNull(scopedProvider, "scopedProvider");
Check.NotNull(contextOptions, "contextOptions");
Check.NotNull(context, "context");
Check.IsDefined(serviceProviderSource, "serviceProviderSource");
_externalProvider = externalProvider;
_services = new ContextServices(scopedProvider);
_serviceProviderSource = serviceProviderSource;
_contextOptions = contextOptions;
_context = context;
_dataStoreServices = new LazyRef<DataStoreServices>(() => _services.DataStoreSelector.SelectDataStore(this));
_modelFromSource = new LazyRef<IModel>(() => _services.ModelSource.GetModel(_context, _dataStoreServices.Value.ModelBuilderFactory));
_dataStore = new LazyRef<DataStore>(() => _dataStoreServices.Value.Store);
_connection = new LazyRef<DataStoreConnection>(() => _dataStoreServices.Value.Connection);
_loggerFactory = new LazyRef<ILoggerFactory>(() => _externalProvider.TryGetService<ILoggerFactory>() ?? new NullLoggerFactory());
_database = new LazyRef<Database>(() => _dataStoreServices.Value.Database);
_stateManager = new LazyRef<StateManager>(() => _services.StateManager);
return this;
}
示例3: ApplyCustomAuthentication
// Generates code for custom authentication and shows the file on IDE editor
public static void ApplyCustomAuthentication(IAbstractEndpoint endpoint, IApplication application, IServiceProvider sp)
{
var solution = sp.TryGetService<ISolution>();
// If the custom file doesn't exist... we will generate it
if (!solution.Find(endpoint.Project.Name + @"\Infrastructure\Authentication.cs").Any())
{
application.Design.Infrastructure.Security.Authentication.LocalNamespace = endpoint.Project.Data.RootNamespace
+ ".Infrastructure";
application.Design.Infrastructure.Security.Authentication.As<IProductElement>()
// We are using Temp as we don't want the generation run on each build
.CreateTempGenerateCodeCommand(sp, "Authentication.cs"
, endpoint.Project.Name + @"\Infrastructure"
, @"t4://extension/a5e9f15b-ad7f-4201-851e-186dd8db3bc9/T/T4/Security/EndpointCustomAuthentication.tt")
.Execute();
}
var item = solution.Find(endpoint.Project.Name + @"\Infrastructure\Authentication.cs").FirstOrDefault();
if (item != null)
{
// Open the file on the IDE Editor
item.As<EnvDTE.ProjectItem>()
.Open(EnvDTE.Constants.vsViewKindCode)
.Visible = true;
}
}
示例4: Initialize
// Initialization
public void Initialize(IApplication app, IProductElement infrastructure, IServiceProvider serviceProvider, IPatternManager patternManager)
{
this.PatternManager = patternManager;
UpdateElementsForUseCase(app, serviceProvider.TryGetService<ISolution>(), serviceProvider);
var handler = new EventHandler((s, e) =>
{
UpdateElementsForUseCase(app, serviceProvider.TryGetService<ISolution>(), serviceProvider);
});
// Listen for a new endpoint initialization
// in order to add the required artifacts (typically menu items)
app.OnInitializingEndpoint += handler;
Command.ElementInitialized += handler;
Event.ElementInitialized += handler;
Component.ElementInitialized += handler;
}
示例5: OnExecute
/// <summary>
/// Occurs when the task is executed.
/// </summary>
/// <param name="serviceProvider">The <see cref="IServiceProvider"/> associated with the task.</param>
protected override void OnExecute( IServiceProvider serviceProvider )
{
Arg.NotNull( serviceProvider, nameof( serviceProvider ) );
INavigationService navigation;
if ( serviceProvider.TryGetService( out navigation ) )
navigation.SetCacheSize( CacheSize );
}
示例6: ApplyCustomAuthentication
// Generates code for custom authentication and shows the file on IDE editor
public static void ApplyCustomAuthentication(IAbstractEndpoint endpoint, IApplication application, IServiceProvider sp)
{
var solution = sp.TryGetService<ISolution>();
// If the custom file doesn't exist... we will generate it
if (!solution.Find(endpoint.Project.Name + @"\Infrastructure\Authentication.cs").Any())
{
application.Design.Infrastructure.Security.Authentication.LocalNamespace = endpoint.Project.Data.RootNamespace
+ ".Infrastructure";
application.Design.Infrastructure.Security.Authentication.As<IProductElement>()
// We are using Temp as we don't want the generation run on each build
.CreateTempGenerateCodeCommand(sp, "Authentication.cs"
, endpoint.Project.Name + @"\Infrastructure"
, @"t4://extension/23795EC3-3DEA-4F04-9044-4056CF91A2ED/T/T4/Security/EndpointCustomAuthentication.tt")
.Execute();
}
var item = solution.Find(endpoint.Project.Name + @"\Infrastructure\Authentication.cs").FirstOrDefault();
if (item != null)
{
// Open the file on the IDE Editor
item.As<EnvDTE.ProjectItem>()
.Open(EnvDTE.Constants.vsViewKindCode)
.Visible = true;
}
// If the custom file doesn't exist... we will generate it
if (!solution.Find(endpoint.Project.Name + @"\Infrastructure\AuthenticationEndpointCode.cs").Any())
{
application.Design.Infrastructure.Security.Authentication.LocalNamespace = endpoint.Project.Data.RootNamespace
+ ".Infrastructure";
application.Design.Infrastructure.Security.Authentication.As<IProductElement>()
// We are using Temp as we don't want the generation run on each build
.CreateTempGenerateCodeCommand(sp, "AuthorizeOutgoingMessages.cs"
, endpoint.Project.Name + @"\Infrastructure"
, (application.TargetNsbVersion == TargetNsbVersion.Version4)
? @"t4://extension/23795EC3-3DEA-4F04-9044-4056CF91A2ED/T/T4/Security/EndpointCustomAutorizeOutgoingMessages.v4.0.tt"
: @"t4://extension/23795EC3-3DEA-4F04-9044-4056CF91A2ED/T/T4/Security/EndpointCustomAutorizeOutgoingMessages.v5.0.tt")
.Execute();
}
}
示例7: Initialize
// This feature requires:
// 1. A menu "Add Authentication" that generates Infrastructure\Security\Authentication Code.
// 2. Add references to the infrastructure project from all the endpoints
// 3. Also, add a new reference when a new endpoint has been instantiated
// 4. Add a menu option for "Customize Authentication" on each endpoint
// This should exist only if the endpoint doesn't have custom authentication already.
// Initialization
public void Initialize(IApplication app, IProductElement infrastructure, IServiceProvider serviceProvider, IPatternManager patternManager)
{
// InitializeAuthenticationValues
InitializeAuthenticationValues(app, serviceProvider.TryGetService<ISolution>(), serviceProvider);
// Listen for a new endpoint initialization
// in order to add the required artifacts (typically menu items)
app.OnInitializingEndpoint += (s, e) =>
{
UpdateEndpointsForAuthentication(app, serviceProvider.TryGetService<ISolution>(), serviceProvider);
};
// Listen for endpoint instantiated, in order to generate
// associated code.
app.OnInstantiatedEndpoint += (s, e) =>
{
GenerateAuthenticationCodeOnEndpoints(app, serviceProvider);
};
app.OnApplicationLoaded += (s, e) =>
{
GenerateAuthenticationCodeOnEndpoints(app, serviceProvider);
};
}
示例8: TryAggregation
private void TryAggregation(PropertyTreeMetaObject value,
QualifiedName name,
PropertyDefinition property,
IServiceProvider serviceProvider)
{
var current = property.GetValue(component, name);
var enumerable = value.Component as IEnumerable;
if (enumerable != null) {
var items = enumerable;
if (!ReferenceEquals(current, items) && enumerable.GetEnumerator().MoveNext()) {
MethodInfo mi = FindAddonMethod(current.GetType(), enumerable);
if (mi == null) {
var errors = serviceProvider.TryGetService(PropertyTreeBinderErrors.Default);
errors.NoAddMethodSupported(component.GetType(), PropertyTreeBinderImpl.FindFileLocation(serviceProvider));
return;
}
foreach (var item in items) {
mi.Invoke(current, new object[] { item });
}
}
}
}
示例9: SetValueCore
private void SetValueCore(PropertyDefinition property,
QualifiedName name,
object ancestor,
PropertyTreeMetaObject value,
object outputValue,
IServiceProvider serviceProvider)
{
var callback = serviceProvider.TryGetService(PopulateComponentCallback.Null);
try {
property.SetValue(component, ancestor, name, value.Component);
} catch (NullReferenceException nre) {
// Normally a "critical" exception, consider it a conversion error
callback.OnConversionException(property.Name, outputValue, nre);
} catch (ArgumentException a) {
callback.OnConversionException(property.Name, outputValue, a);
} catch (Exception ex) {
if (Require.IsCriticalException(ex))
throw;
callback.OnConversionException(property.Name, outputValue, ex);
}
}
示例10: BindStreamingSource
public override PropertyTreeMetaObject BindStreamingSource(StreamContext input, IServiceProvider serviceProvider)
{
var ss = StreamingSource.Create(this.ComponentType) ?? new PropertyTreeSource();
if (ss == null) {
var errors = serviceProvider.TryGetService(PropertyTreeBinderErrors.Default);
errors.CouldNotBindStreamingSource(this.ComponentType, PropertyTreeBinderImpl.FindFileLocation(serviceProvider));
return this;
}
// Hydrate the existing instance
ss.Load(input, this.Component);
return this;
}
示例11: TryConvertFromText
internal bool TryConvertFromText(string text,
IServiceProvider serviceProvider,
out object result)
{
// TODO In some cases, this will be treated as if a streaming source hydration
Type neededType = this.ComponentType;
PropertyDescriptor property = null;
object value = text;
var context = serviceProvider.TryGetService<ITypeDescriptorContext>();
if (context != null) {
property = context.PropertyDescriptor;
// Get type from property providers
var pp = context.Instance as IPropertyProvider;
if (pp != null) {
neededType = property == null ? typeof(string) : (pp.GetPropertyType(property.Name) ?? typeof(string));
}
}
// Apply concrete classes
var cp = neededType.GetConcreteClass() ?? neededType;
var conv = TypeHelper.GetConverter(property, cp);
result = conv.ConvertFrom(context, Thread.CurrentThread.CurrentCulture, value);
return true;
}
示例12: Initialize
public void Initialize(IServiceProvider serviceProvider)
{
if (HasBeenAlreadyInitialized)
{
if (this.ToolBarExtension != null)
{
this.ToolBarExtension.CheckForEnablingSolution();
}
return;
}
HasBeenAlreadyInitialized = true;
this.WireSolutionEvents();
this.DetailsWindowManager = serviceProvider.TryGetService<IDetailsWindowsManager>();
if (this.DetailsWindowManager != null)
{
this.DetailsWindowManager.Show();
}
this.SolutionBuilderViewModel = this.PatternWindows.GetSolutionBuilderViewModel(serviceProvider);
var toolWindow = this.PatternWindows.ShowSolutionBuilder(serviceProvider);
if (toolWindow != null)
{
var content = toolWindow.Content as UserControl;
var contentGrid = content.Content as Grid;
foreach (var theitem in contentGrid.Children)
{
if (theitem is ScrollViewer)
{
this.Scrollviewer = (theitem as ScrollViewer);
}
}
foreach (var item in contentGrid.Children)
{
if (item is StackPanel)
{
foreach (var subitem in (item as StackPanel).Children)
{
if (subitem is StackPanel)
{
var toolbarSP = subitem as StackPanel;
this.ToolBarExtension = new ToolbarExtension
{
ContentScrollViewer = Scrollviewer,
ServiceProvider = serviceProvider
};
toolbarSP.Children.Add(this.ToolBarExtension);
}
}
}
}
}
}
示例13: TryGetWindowFrame
/// <summary>
/// Tries to the get window frame for the given file.
/// </summary>
/// <param name="serviceProvider">The service provider.</param>
/// <param name="fileName">The file name.</param>
/// <param name="windowFrame">The window frame.</param>
/// <returns>
/// <c>true</c> if fetching the window frame was successful, otherwise <c>false</c>.
/// </returns>
private static bool TryGetWindowFrame(IServiceProvider serviceProvider, string fileName, out IVsWindowFrame windowFrame)
{
IVsUIShellOpenDocument openDocument;
if (!serviceProvider.TryGetService(out openDocument))
{
windowFrame = null;
return false;
}
IOleServiceProvider oleServiceProvider;
IVsUIHierarchy hierarchy;
uint itemid;
var viewKind = new Guid(EnvironmentConstants.vsViewKindTextView);
if (ErrorHandler.Failed(openDocument.OpenDocumentViaProject(
fileName,
ref viewKind,
out oleServiceProvider,
out hierarchy,
out itemid,
out windowFrame)))
{
return false;
}
return windowFrame != null;
}
示例14: InitializeContainer
private IServiceLocator InitializeContainer(IServiceProvider services)
{
using (tracer.StartActivity(Strings.DevEnvFactory.CreatingComposition))
{
// Allow dependencies of VS exported services.
var composition = services.TryGetService<SComponentModel, IComponentModel>();
// Keep track of assemblies we've already added, to avoid duplicate registrations.
var addedAssemblies = new Dictionary<string, Assembly>();
// Register built-in components from Clide assembly.
var clideAssembly = Assembly.GetExecutingAssembly();
addedAssemblies.Add(clideAssembly.Location.ToLowerInvariant(), clideAssembly);
// Register hosting package assembly.
var servicesAssembly = services.GetType().Assembly;
addedAssemblies[servicesAssembly.Location.ToLowerInvariant()] = servicesAssembly;
var installPath = GetInstallPath(services);
foreach (var providedAssemblyFile in services.GetType()
.GetCustomAttributes<ProvideComponentsAttribute>(true)
.Select(attr => Path.Combine(installPath, attr.AssemblyFile)))
{
if (!File.Exists(providedAssemblyFile))
throw new InvalidOperationException(Strings.DevEnvFactory.ClideProvidedComponentsNotFound(
services.GetType().FullName, Path.GetFileName(providedAssemblyFile), providedAssemblyFile));
var providedAssembly = Assembly.LoadFrom(providedAssemblyFile);
if (!addedAssemblies.ContainsKey(providedAssembly.Location.ToLowerInvariant()))
addedAssemblies.Add(providedAssembly.Location.ToLowerInvariant(), providedAssembly);
}
var packageManifestFile = Path.Combine(installPath, "extension.vsixmanifest");
if (File.Exists(packageManifestFile))
{
tracer.Info(Strings.DevEnvFactory.ExtensionManifestFound(packageManifestFile));
var manifestDoc = XDocument.Load(packageManifestFile);
ThrowIfClideIsMefComponent(manifestDoc);
// NOTE: we don't warn anymore in this case, since a single package may have
// a mix of plain VS exports as well as clide components.
// Since we use CommonComposition, only the types with the ComponentAttribute
// will be made available in the Clide container, not the others, and no
// duplicates would be registered.
//WarnIfClideComponentIsAlsoMefComponent(packageManifestFile, manifestDoc);
foreach (string clideComponent in GetClideComponents(manifestDoc))
{
var assemblyFile = Path.Combine(installPath, clideComponent);
tracer.Info(Strings.DevEnvFactory.ClideComponentDeclared(clideComponent, assemblyFile));
if (clideComponent == ClideAssembly)
{
tracer.Warn(Strings.DevEnvFactory.ClideNotNecessaryAsComponent(clideComponent));
continue;
}
if (!File.Exists(assemblyFile))
throw new InvalidOperationException(Strings.DevEnvFactory.ClideComponentNotFound(packageManifestFile, clideComponent, assemblyFile));
var componentAssembly = Assembly.LoadFrom(assemblyFile);
if (!addedAssemblies.ContainsKey(componentAssembly.Location.ToLowerInvariant()))
addedAssemblies.Add(componentAssembly.Location.ToLowerInvariant(), componentAssembly);
}
}
else
{
tracer.Info(Strings.DevEnvFactory.ExtensionManifestNotFound(packageManifestFile));
}
var catalog = new ComponentCatalog(addedAssemblies.Values.ToArray());
var providers = composition != null ?
new ExportProvider[] { new ServicesExportProvider(services), composition.DefaultExportProvider } :
new ExportProvider[] { new ServicesExportProvider(services) };
var container = new CompositionContainer(catalog, providers);
// Make the service locator itself available as an export.
var serviceLocator = new ServicesAccessor(services, new Lazy<IServiceLocator>(() => serviceLocators[services]));
container.ComposeParts(serviceLocator);
return new ExportsServiceLocator(container);
}
}
示例15: FindFileLocation
internal static FileLocation FindFileLocation(IServiceProvider serviceProvider)
{
var loc = serviceProvider.TryGetService(Utility.NullLineInfo);
string uri = Convert.ToString(serviceProvider.TryGetService(Utility.NullUriContext).BaseUri);
return new FileLocation(loc.LineNumber, loc.LinePosition, uri);
}